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.


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!