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.

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Giving Information to Functions

10,331 Points

Why would Dave store the information to be returned in a variable, instead of just calling it directly?

For example, Dave wrote this:

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

Why would he not do this instead, to save lines?

function getRandomNumber() {
   return Math.floor( Math.random() * 6 ) + 1;

The only reason I can imagine is because a longer value to return could get messy on one line, but in this case, where it's quite small, does it make a difference?

Thank you, friends.

3 Answers

Steven Parker
Steven Parker
218,487 Points

I'm with you.

I'd write this exactly like your second example. I'm just speculating that it's done like this in the video because creating a variable for a result from some calculations and then returning that variable is a common theme in development. But for this particular case that variable is clearly not needed.

It's a common practice in the development community. You don't have to write it like that, you can do it your way, but it makes it easier to throw the results in a variable like that because then you can just call that variable anytime. Actually he should of made that variable global and call it in the function.


var randomNumber = Math.floor( Math.random() * 6 ) + 1; function getRandomNumber() { return randomNumber; } then you can call that variable anytime in any function you need. Hope this helps : )

That's right Peterson....