Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Marco Fernandes
Marco Fernandes
663 Points

Returning var instead of function

In the code below I would like the alert box to display a random number. But it only works when I type alert ( getRandomNumber); . Why is that it won't work if I type alert (randomNumber); ? For me, it makes sense to type alert (randomNumber); because this is the returned value.

Can someone break it down for me why it is incorrect?


function getRandomNumber() { var randomNumber = Math.floor( Math.random() * 6 ) + 1; return randomNumber; }


1 Answer

Steven Parker
Steven Parker
216,057 Points

The variable named "randomNumber" only exists inside the function. Only the value is returned to the code where the function is invoked.

I also wouldn't expect "getRandomNumber" to work by itself — when you invoke ("call") a function, you must include parentheses after the name. But this should work:

alert(getRandomNumber());  // invoke "getRandomNumber" and display the result