HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Random

The Math.random() method returns a random number between 0 (inclusive), and 1 (exclusive). This is the foundation for all randomness in JavaScript, from games to security tokens.


Mathematical Range

Math.random() always returns a fractional number (a decimal).

Math.random(); // returns something like 0.743219...

Generating Random Integers

To get a whole number (an integer), you must combine Math.random() with Math.floor(). Multiplying by a number sets the upper limit.

Examples:

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

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

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

A Proper Random Function

Instead of writing the math every time, it is best practice to use a reusable function that takes a minimum and maximum value.

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

This function will return a random number between min (included) and max (excluded).

Technical Note: If you want the max value to be included as well, use (max - min + 1) in the multiplication.

Key Points to Remember

  • Math.random() returns a decimal between 0 and 0.999...
  • Never returns 1 exactly
  • Use Math.floor() to convert decimals to integers
  • Multiply by (max - min) to scale the range
  • Add min to shift the starting point
  • For security-sensitive applications (like cryptography), use crypto.getRandomValues() instead of Math.random()