Random in JavaScript

Math.random()

Math.random() Returns a random number between 0 (inclusive) and 1 (exclusive):

Example

Math.random();				// Returns a random number

Try It Yourself

Math.random() Always returns a number less than 1.

JavaScript Random Integer

Math.random() With Math.floor() Used together to return a random integer.

Example

Math.floor(Math.random() * 10);		// Returns a number between 0 and 9

Try It Yourself

Example

Math.floor(Math.random() * 11);		// Returns a number between 0 and 10

Try It Yourself

Example

Math.floor(Math.random() * 100);	// Returns a number between 0 and 99

Try It Yourself

Example

Math.floor(Math.random() * 101); // Returns a number between 0 and 100

Try It Yourself

Example

Math.floor(Math.random() * 10) + 1; // Returns a number between 1 and 10

Try It Yourself

Example

Math.floor(Math.random() * 100) + 1; // Returns a number between 1 and 100

Try It Yourself

An appropriate random function

As you can see from the example above, it is a good idea to create a random function to generate all random integers.

This JavaScript function always returns a number between minand maxbetween (exclusive):

Example

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

Try It Yourself

This JavaScript function always returns a number between min and maxbetween (inclusive):

Example

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Try It Yourself