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! While you're at it, check out some resources Treehouse students have shared here.
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 trialKirby Abogaa
3,058 PointsUndefined
Can anyone tell what makes the code undefined?
<script>
var randomNumber = getRandomNumber(2);
function getRandomNumber(upper) {
Math.floor( Math.random() * upper ) + 1 ;
}
console.log(randomNumber);
</script>
2 Answers
Grace Kelly
33,990 PointsHi Kirby the code above gives you an undefined value because the function does not return a value, we return a value by doing the following:
function getRandomNumber(upper) {
num = Math.floor( Math.random() * upper ) + 1; //assign the random value to num variable
return num; //return the variable
}
or by simply doing
function getRandomNumber(upper) {
return Math.floor( Math.random() * upper ) + 1; //return the random number
}
By doing this, when you log out the randomNumber variable it will show you a number
Hope that helps!!
Kirby Abogaa
3,058 PointsThanks Grace!
I actually just realized the solution and was about to post it here. But hey, you did it already!
Cheers!
Grace Kelly
33,990 Pointsno worries glad you figured it out!! :)