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 trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops For Loops

Undefined

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

Hi 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!!

Thanks Grace!

I actually just realized the solution and was about to post it here. But hey, you did it already!

Cheers!

no worries glad you figured it out!! :)