Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Random

Math.random()

Math.random() returns a random number in the range of 0 (inclusive) to 1 (exclusive).

Example

// Returns a random number:
Math.random();
Math.random() consistently returns a number that is less than 1.

JavaScript Random Integers

Combining Math.random() with Math.floor() can produce random integers.

JavaScript does not have a distinct integer type; instead, it uses numbers without decimals to represent integers.

Example

// Returns a random integer from 0 to 9:
Math.floor(Math.random() * 10);

Example

// Returns a random integer from 0 to 10:
Math.floor(Math.random() * 11);

Example

// Returns a random integer from 0 to 99:
Math.floor(Math.random() * 100);

Example

// Returns a random integer from 0 to 100:
Math.floor(Math.random() * 101);

Example

// Returns a random integer from 1 to 10:
Math.floor(Math.random() * 10) + 1;

Example

// Returns a random integer from 1 to 100:
Math.floor(Math.random() * 100) + 1;

A Proper Random Function

As illustrated in the examples above, it’s advisable to create a dedicated random function for generating random integers. This JavaScript function consistently returns a random number within the range of min (inclusive) and max (exclusive).

Example

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

This JavaScript function consistently returns a random number within the range of min and max, including both endpoints.

Example

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