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 trialAakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsLoop conditions
Though there is a very little difference between my and Dave's code , still I want to ask which is better approach to follow ?
Dave's Code
-
var upper = 10000;
var randomNumber = getRandomNumber(upper);
var guess ;
var attempts = 0;
function getRandomNumber(upper){
return Math.floor(Math.random()* 10000 + 1);
}
while ( gues !== randomNumber){
guess = getRandomNumber( upper );
attempts += 1;
}
document.write("<p>The random number was "+ randomNumber + "</p>");
document.write("<p>It took the computer "+ attempts + " attempts to guess the correct number</p>");
My Code-
var userInput = parseInt(prompt("Enter a number"));
var attempts = 0;
var guess ;
function getRandomNumber(){
guess = Math.floor(Math.random()* 10000 + 1);
return guess;
}
while( userInput !== guess ){
getRandomNumber();
attempts ++;
}
document.write("<p>The random number was "+ userInput + "</p>");
document.write("<p>It takes "+ attempts + " times to guess the correct number</p>");
Please review. Thanks
1 Answer
Jordan Stokes
Full Stack JavaScript Techdegree Graduate 27,292 PointsDave's code is more practical for one simple reason: reusability.
The function in your code cannot be used without changing the global variable "guess." However, if you just return a random number, and do not set a global variable, the "getRandomNumber" function can be called elsewhere, for various purposes. Typically, this is what you want, since the entire purpose of functions is to keep your code DRY, and prevent yourself from repeating the same code over and over again.