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


3,274 Points

Difference between a function and variable?

Hi there,

couldn't you just declare a variable instead a function, like:

var randomNumber = Math.floor( Math.random() * 6 ) + 1;

instead of:

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


3 Answers

Hey Simon, the function:

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

will return a different random number every time you call:


in your code. Whereas

var RandomNumber = Math.floor(Math.random()*10 + 1);

will generate a single random number and store that number as a variable, RandomNumber. So, if you want a single random number you can assign it to a variable. However, if you want your code to generate different random numbers each time you run it, you should use a function. I hope that helps. Happy coding!

Daniel Hernandez
Daniel Hernandez
13,437 Points

Functions are more fluid and allow for different inputs, whereas a variable will always be predefined. It depends on what you are doing to which is more fitting. The above answer is very much correct.

3,274 Points

Thank you both! That answers my question!