Generate A Random Number in Javascript

Generate A Random Number in Javascript

Here is a very easy function in Javascript to generate a random number.

function getRandomNumber(upper) { 
return Math.floor( Math.random() * upper ) + 1; 
}

All you need to do is pass in a value that will be the limit that it goes up to.

How To Apply It

Listed below is a little program that generates a random number then the computer tries to guess it. Once it does, it writes out the number and the number of attempts.

var upper = 20;
var randomNumber = getRandomNumber(upper);
var guess;
var attempts = 0;
function getRandomNumber(upper) {
 return Math.floor( Math.random() * upper ) + 1;
}
while(guess !== randomNumber) {
 guess = getRandomNumber(upper);
 document.write("My guess is: " + guess + "</p>");
 attempts +=1;
}
document.write("<p>The random number was: "+ randomNumber + "</p>");
document.write("<p>It took the computer "+ attempts + " attempts to get it right.</p>");