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

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?

Thanks.

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

alert(getRandomNumber);

1 Answer

Steven Parker
Steven Parker
229,644 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