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
Edgar Gil
13,322 PointsQuestion regarding function and var
As you can see a function with that name "getRandomNumber" was created , then is store in "Var randomNumber". My question is can't we just use. getRandomNumber(#);
instead of. var randomNumber;
The only reason I think is use, is for less typing.
function getRandomNumber( upper ) { var num = Math.floor(Math.random() * upper) + 1; return num; } var randomNumber = getRandomNumber(10);
var guess; var guessCount = 0; var guessCorrect=false;
do{ guess=prompt("i'm thinking a number between 1 and 9.What it is?") guessCount+=1; if(parseInt(guess)===randomNumber){ guessCorrect=true; } } while(! guessCorrect)
document.write("You guessed the number"); document.write("it took "+guessCount+"tries to guess"+randomNumber);
2 Answers
Momchil Tsenov
5,709 PointsHi Edgar,
in this example getRandomNumber(#) - # represents the argument of the function. In other words the condition so if you do getRandomNumber(10) for example it will generate a number between 1 and 10 for you. However you still need to store that number somewhere so you still need to use a variable and it is true running the function again and again will generate a different random number every time.
Hope this helps
Edgar Gil
13,322 PointsThank you i understand it now!
JP Nothard
3,846 PointsHi Edgar,
Basically what you are doing is using randomNumber to store the random number. So you are using a single random number when you run it.
If you replace the the variable with the function you will be generating a new random number each time the function getRandomNumber() is called. This would make it hard to compare and will give you false/confusing results.
I hope this makes sense.
Edgar Gil
13,322 PointsThank you i understand it now!
Olga Kireeva
9,609 PointsOlga Kireeva
9,609 PointsIn programming it's very common to assign to a variable a function result. Using a variable makes the code easy to read and maintain. When you will have many lines of code you'll be able to appreciate this strategy.