Generating a random number

To generate a random number in JavaScript, use the built-in function Math.random(). This function returns a pseudo-random number between 0 and 1, which with a little massaging can produce the desired effect. The following code creates a random number between 0-10:

var randomnumber=Math.floor(Math.random()*11)

We use Math.floor() in conjunction so the final number is an integer. To generate a random number between, say, 0-100, simply change "11" above to "101".

Now, if you wish to alter the range of the number to something other than starting from \"0\", such as 55-200, simple logic tells us we can do this instead:

var randomnumber=Math.floor(Math.random()*145)+55

And there you have it!

var randomnumber=Math.floor(Math.random()*11)

Some of you may be curious as to why Math.floor() instead of Math.round() is used in our technique to round off the random number to an integer. While both methods successfully round off its containing parameter to an integer within the designated range, Math.floor does so more \"evenly\", so the resulting integer isn\'t lopsided towards either end of the number spectrum. In other words, a more random number is returned using Math.floor(). Also as a side note, the random number generator in JavaScript is seeded from the current time, just like in Java.