JavaScript Generate a Random 6-Digit Number
In this article
To generate a random six-digit integer in JavaScript, use Math.floor(100000 + Math.random() * 900000). It returns a value from 100000 through 999999, inclusive, so the result always contains six digits when written as a number.
How the six-digit range works
JavaScript’s Math.random() returns a pseudorandom decimal greater than or equal to 0 and less than 1. Multiplying it by 900000 produces a value in the range 0 up to, but not including, 900000. Adding 100000 shifts that range to 100000 up to, but not including, 1000000. Finally, Math.floor() rounds down to an integer, giving every whole number from 100000 to 999999 as a possible result.
The endpoints matter. A common but incorrect attempt is Math.floor(Math.random() * 1000000). That generates integers from 0 to 999999, so most results have fewer than six digits. Another frequent mistake is multiplying by 899999: because Math.random() never returns 1, that approach does not include the upper endpoint. The 900000-wide range is the straightforward way to cover all 900,000 six-digit integers.
Use a reusable function
If the same operation appears in several places, put it in a function:
function randomSixDigitNumber() {
return Math.floor(100000 + Math.random() * 900000);
}
const code = randomSixDigitNumber();
console.log(code);
Each call produces a new pseudorandom result. It is reasonable for non-sensitive uses such as a temporary display value, a sample number in a demo, or a casual game. It does not guarantee a different result each time: repeated calls can produce the same number.
You can also write the range using minimum and maximum values, which can make the intent easier to adapt:
const min = 100000;
const max = 999999;
const number = Math.floor(Math.random() * (max - min + 1)) + min;
The + 1 includes the maximum because the random fraction is below 1. For any inclusive integer range, the general pattern is Math.floor(Math.random() * (max - min + 1)) + min.
When the result must be a six-character code
A number and a code that looks numeric are not always the same thing. Numbers do not preserve leading zeros. If you need exactly six characters, including values such as 004271, treat the result as a string rather than a number.
For a uniformly selected six-digit string that can begin with zero, choose an integer from 0 through 999999 and pad it:
const code = String(Math.floor(Math.random() * 1000000)).padStart(6, "0");
This can produce strings from 000000 to 999999. Use this form for formatting or examples when a leading zero is allowed. If the requirement says the code must be a six-digit integer, rather than six characters, use the 100000-to-999999 range instead. Converting the padded string back to a number would remove its leading zeros.
Randomness, repeats, and uniqueness
Math.random() is a pseudorandom generator: it produces values that appear random for ordinary programming tasks, but it is not designed to protect secrets. The result is not a promise of uniqueness, and choosing a larger range does not prevent collisions. A six-digit integer has 900,000 possible values, so a program that generates many of them should expect repeats eventually.
If a set of values must be unique, store the values already assigned and check each new candidate before accepting it. For a small set, a Set is a convenient option:
const used = new Set();
function uniqueSixDigitNumber() {
if (used.size >= 900000) {
throw new Error("No unused six-digit numbers remain");
}
let value;
do {
value = Math.floor(100000 + Math.random() * 900000);
} while (used.has(value));
used.add(value);
return value;
}
This check only works within the lifetime and scope of that set. In a multi-user application, uniqueness usually needs to be enforced by a shared database or service, because separate processes can independently choose the same number.
For security-sensitive codes
Do not use Math.random() for authentication codes, password-reset tokens, one-time passcodes, or other values an attacker might guess. For those tasks, use the Web Crypto API, which provides cryptographically secure random values in supported browsers.
To create an unbiased six-digit integer in the range 100000–999999, draw a 32-bit value and reject values above the largest evenly divisible range:
function secureSixDigitNumber() {
const range = 900000;
const limit = Math.floor(2 ** 32 / range) * range;
const values = new Uint32Array(1);
let value;
do {
crypto.getRandomValues(values);
value = values[0];
} while (value >= limit);
return 100000 + (value % range);
}
The rejection step avoids a small statistical bias that would occur if every 32-bit value were reduced with a remainder alone. This example is for browser environments where crypto.getRandomValues() is available. Secure generation alone does not make an authentication system safe: codes should also expire, have limited attempts, and be handled over a protected connection.
Common mistakes and practical choices
- Need a six-digit integer: use the 100000–999999 range.
- Need six characters with possible leading zeros: generate 0–999999 and use
padStart(6, "0"). - Need a secret or verification code: use a cryptographically secure source, not
Math.random(). - Need unique assignments: check against stored values and enforce uniqueness in the shared system that owns the data.
- Need a repeatable result for a demonstration: use a fixed example value rather than depending on random output.
Remember that a six-digit numeric code has a limited search space. Even if it is generated securely, it should not be treated as a strong standalone password. Security depends on how the code is delivered, how long it remains valid, and how many guesses are allowed.
Frequently Asked Questions
How do I generate a random 6-digit number in JavaScript?
Use Math.floor(100000 + Math.random() * 900000) for a non-sensitive integer from 100000 to 999999.
Can the number start with zero?
A JavaScript number has no preserved leading zeros. Generate a value from 0 to 999999 and format it with String(value).padStart(6, "0") if you need a six-character code that can start with zero.
Does Math.random produce unique numbers?
No. It can return a value that has appeared before. Track previously used values and check each candidate if uniqueness is required.
Is Math.random secure for OTPs?
No. Use a cryptographically secure random source such as the browser’s crypto.getRandomValues() for security-sensitive codes, and apply expiration and attempt limits.
Why does Math.floor(Math.random() * 1000000) sometimes return fewer than six digits?
That expression includes values from 0 to 99999, which have fewer than six digits when displayed as numbers. Raise the minimum to 100000, or format the result as a padded string if zeros should be allowed.