Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Math.random() — generating a random number

Math.random() returns a Number in [0, 1), with an approximately uniform distribution. It suits simple random choices, but provides neither cryptographic security nor a reproducible seed.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

Math.random()

Math.random() is an ECMAScript standard-library function, not a separate browser API. It takes no parameters and returns a Number satisfying 0 <= value && value < 1: zero is possible, while one is excluded. The distribution is approximately uniform, so a small sample need not look evenly spread.

The algorithm is implementation-defined. The API exposes no way to set a seed or replay a sequence. The standard does not guarantee cryptographic security: do not use this function for passwords, tokens, or other secrets.

For a die, use Math.floor(Math.random() * 6) + 1 to obtain an integer from 1 through 6. Do not replace Math.floor with Math.round, because that changes the outcome probabilities. When scaling to other ranges, account for floating-point rounding.

The example accepts a random function that defaults to Math.random. Constant test functions let you check the mapping without guessing a random number; a separate call checks the range of a real result.

Examples

function rollDie(random = Math.random) {
  return Math.floor(random() * 6) + 1;
}

console.log(rollDie(() => 0));
console.log(rollDie(() => 0.5));
console.log(rollDie(() => 0.999));

const value = Math.random();
console.log(value >= 0 && value < 1);

Result

1
4
6
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources