<html>
<body>
<script type="text/javascript">
function createPerson (name){
var o = new Object();
o.name = name;
return o;
};
var person1 = createPerson ("Nicholas");
alert(person1.name);
</script>
</body>
</html>
Why do we have to
return o
?
What does “return” mean?
returnis a JavaScript keyword that causes the function it’s placed in to exit with the specified value (called the “return value”).In this case, it causes the
createPerson()function to come to an end, returning theoobject to the caller of the function.The
oobject, once returned fromcreatePerson(), then gets assigned to theperson1variable.So the net result is that control flow starts here
then jumps into the
createPerson()function, which creates a new object representing a person with the name “Nicholas”, then returns it, which brings the execution back to that line, withperson1getting the newly created person that the function returned.