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 Basics (Retired) Creating Reusable Code with Functions Giving Information to Functions

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
231,275 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.

like,

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....