Link to home
Start Free TrialLog in
Avatar of jskfan
jskfanFlag for Cyprus

asked on

Return Keyword in Javascript function.

Return Keyword in Javascript function.
I have the code below that runs and gets the results as expected:
var person = function(name,age,state){
var temp={};
	temp.name = name;
	temp.age = age;
	temp.state = state;

temp.printperson=function(){
	document.write(this.name);
};
[b]return[/b] temp;
};

var person1=person('Omar','25','CS');

person1.printperson();

Open in new window


I would like to know what the keyword "return" does in the code above.

Thank you
SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jskfan

ASKER

online definition :
In JavaScript, return statements cease execution in a function and return a value to the caller; JavaScript functions require an explicit return statement for returning the result of an expression (the value) from a function

in the example above, the RETURN keyword is already at the end of the function, and the RETURN does not return any value

the way i understand the code above is:

this will assign values to the parameters:
var person1=person('Omar','25','CS');

and this will call the function :
person1.printperson();
and the RETURN does not return any value

It is returning a value, it is returning the "temp" object .

So when you are calling the "person" function, you are passing in those 3 parameters and it is returning an object. That object (the one originally called "temp" inside the function) then gets assigned into the "person1" variable.
Avatar of jskfan

ASKER

probably this statement confused me:
temp.printperson=function(){
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jskfan

ASKER

if someone can explain it line by line, that might make sense.

for instance here:
***var person1=person('Omar','25','CS');
 we are passing the Values to the first  Function()

****temp.name = name;
      temp.age = age;
      temp.state = state;

then the values got assigned to the elements of object Temp



****temp.printperson=function()
this is  "element" temp function instead of attribute

=========
now what values are in the temp object ,when using return temp;    ??

and what is this statement below doing ? is it calling the printperson() function
person1.printperson();

if I understand person1 is an instance of person, and not of the temp, how come it is calling printperson
*****
========================
to sum it up:
If someone can break it down line by line, and explain how those functions or objects are tied to each other, then that might help
Avatar of jskfan

ASKER

Thanks