Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

SeHyun Choi
3,441 PointsReturn in Javascript function
I have question about following code...
function getRandomNumber( upper ) { var randomNumber = Math.floor( Math.random() * upper ) + 1 ; return randomNumber;
}
console.log(getRandomNumber(54));
so basically what "return" is doing is....
It exits the function called getRandomNumber and then get the parameter in this case 54 and then bring it back to variable randomNumber?
Am I understanding this correctly?
1 Answer

Steven Parker
225,664 PointsThe "return
" keyword does two things. It ends the function, but it also passes back a value to the point in the code where the function was called.
The value passed back in this case is whatever is stored in the variable "randomNumber
". We can't predict what the value will be even if we know what "upper" is because of the "random" part of the formula.
SeHyun Choi
3,441 PointsSeHyun Choi
3,441 PointsThank you for the reply. But I am still confused..
function getRandomNumber( upper ) { var randomNumber = Math.floor( Math.random() * upper ) +1;
}
alert(getRandomNumber(6));
when I do this why do I get alert message saying "undefined"?
I am confused because in original question I typed return randomNumber. Then for console.log() I typed getRandomNumber instead of randomNumber. Please help I'm so confused.
Steven Parker
225,664 PointsSteven Parker
225,664 PointsThis version has no "return". Remember that the second thing a "return" does is to pass back the value. So when no value is passed back to the "alert", it shows "undefined".
SeHyun Choi
3,441 PointsSeHyun Choi
3,441 PointsThank you.