JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,609 Points

Loop 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
Jordan Stokes
Full Stack JavaScript Techdegree Graduate 22,909 Points

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