JavaScript Math.random() returns a pseudo-random number in the half-open range [0, 1)—from zero up to, but not including, one. In practice you almost always scale that value to pick integers in a range, shuffle arrays, or sample between two bounds. If you combine randomness with trigonometry, keep angles in radians (see degrees to radians in JavaScript) so formulas stay consistent with Math.sin / Math.cos.
Environment: Node.js v20.18.2.
Math.random()is different every run; where the article needs a stable illustration, a fixed sample (for example0.42) is used and called out in the text.
Math.random Syntax
Math.random()The return value always satisfies 0 ≤ value < 1 (half-open interval).
Method 1: Generate a Random Decimal
const value = Math.random();
console.log(value >= 0 && value < 1);You should see one line logging true.
The exact value changes each time, but it remains at least 0 and less than 1.
Method 2: Generate a Random Number in a Range
Formula:
Math.random() * (max - min) + minUsing a fixed sample random value of 0.42, the formula for 0 to 10 becomes:
const random = 0.42;
const value = random * 10;
console.log(value);You should see one line logging 4.2.
With real random output, replace random with Math.random().
Method 3: Generate a Random Integer
For an integer from 1 to 6, use Math.floor() with Math.random().
const random = 0.42;
const dice = Math.floor(random * 6) + 1;
console.log(dice);You should see one line logging 3.
Real dice code uses:
const dice = Math.floor(Math.random() * 6) + 1;Security Note for Math.random
Math.random() is not cryptographically secure. Do not use it for passwords, tokens, session IDs, or security-sensitive random values. In browsers, use crypto.getRandomValues() for secure random bytes.
Common Questions About Math.random
What range does Math.random return?
It returns a number greater than or equal to 0 and less than 1.
Can Math.random return 1?
No. The upper bound is exclusive, so 1 is not returned.
How do I generate a random integer in JavaScript?
Use Math.floor(Math.random() * count) + start, adjusted for your range.
Summary
Math.random() is fine for UI and games; use crypto.getRandomValues when the result protects data or accounts.
JavaScript Math.random() generates a pseudo-random decimal in the range 0 <= value < 1. Multiply and shift that value to create custom ranges, and combine it with Math.floor() for random integers. The exact result changes on each run, and Math.random() is not suitable for cryptographic security.
