JavaScript

Generate a casual random integer in a range

For a non-security task, use Math.random with a half-open integer range: minimum inclusive, maximum exclusive. Naming both boundaries helps avoid off-by-one errors in games or sample data.

Worked example

Node.js example · save as example.mjs and run node example.mjs

function randomInteger(min, max) {
  if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || max <= min)
    throw new Error("Invalid bounds");
  return Math.floor(Math.random() * (max - min)) + min;
}
const result = randomInteger(1, 7);
console.log(result >= 1 && result < 7);

How it works

Multiplication scales the random fraction to the range width. Floor picks an integer bucket and adding the minimum shifts that bucket into the requested interval. A six-sided die uses boundaries 1 and 7 rather than 1 and 6.

Limits and mistakes

Math.random is not suitable for passwords, tokens, or cryptographic decisions. Floating-point precision also limits very large ranges; this helper is intended for small practical intervals, not sampling every safe integer uniformly.

Check the result

The example should print true. Generate many sample values and verify they stay inside the interval, but do not treat that check as proof of security or exact statistical uniformity.

Sources

Reference documentation for the behavior used in this guide: