JavaScript Math.random method
INTERACTIVE CORNER
use this simple seeded JavaScript random number generator to guess a number between 1 and 10.
Your guess displays here!
This JavaScript tutorial aims to demonstrate the floor() and random() methods of the JavaScript Math object.
Math.random
The JavaScript function Math.random() randomly returns a pseudo-random number between 0 (inclusive) and 1 (exclusive). The random number generator is seeded from the current time and chosen from an entropy pool (each browser differs), so every time you run it, you'll get different results. The random number also returns decimal places (i.e. 0.46669).
Math.floor
The JavaScript Math.floor() function will always round a decimal number down to a whole number. So it makes sense to wrap the random() method with the floor() method to always return an integer.
Math.floor(Math.random()*x+1)
Because the above function has a chance to return 0, +1 is used is to ensure all results are between 1 and whatever variable you use.
Browser Tests
Paste this into your browsers address bar and press [Enter] a few times for an example of random numbers seeded to time.
javascript:alert(Math.random() * 2 > 1);
This will either return true or false...