Generate a random string ID in JavaScript
Intermediate · 4 min read
Random strings like 'aZ3kP9' are everywhere in web apps: ids for elements on a page, names for uploaded files, short codes in links, keys in a cache. In this tutorial you will write randomId(length), a function that builds one from a list of allowed characters.
Along the way you will learn how Math.random picks an index, why Math.floor is safe and Math.round is not, how to make random code testable, and when Math.random is not good enough at all. You need to know loops, strings and what a function is.
Math.random in one minute
Math.random() returns a random decimal number from 0 up to, but never including, 1. For example 0.0, 0.5 or 0.9999. To turn that into a position in a list of n items, multiply by n and round down with Math.floor:
console.log(Math.floor(0 * 62)); // 0
console.log(Math.floor(0.5 * 62)); // 31
console.log(Math.floor(0.9999 * 62)); // 61
With 62 characters, the positions run from 0 to 61. Because Math.random() is always below 1, Math.floor can never reach 62.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
20 Generate a random ID string
fairBuild a random string of a given length from a supplied character list. Then decide whether Math.random is good enough.
Stuck? Three hints, smallest first
- 1.
Math.floor(Math.random() * chars.length)picks an index. - 2. Make the randomness a parameter, so a test can supply a known sequence.
- 3.
Math.randomis not cryptographically secure.crypto.getRandomValuesis.
Step 1: the alphabet
The allowed characters go in one string. Each character has a position, and chars[i] reads it:
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
console.log(ALPHABET.length); // 62
console.log(ALPHABET[0]); // 'A'
console.log(ALPHABET[61]); // '9'
26 capitals, 26 small letters and 10 digits make 62.
Step 2: pick one character at a time
Loop length times. Each time, pick a random position and add that character to the result:
function firstTry(length) {
let out = '';
for (let i = 0; i < length; i++) out += ALPHABET[Math.floor(Math.random() * ALPHABET.length)];
return out;
}
console.log(firstTry(8).length); // 8
The result is different every time you run it, so the only thing this line can promise is the length.
Step 3: why not Math.round?
Math.round rounds to the nearest whole number, so it sometimes rounds up. Near the top of the range, that goes one past the end:
console.log(Math.round(0.995 * 62)); // 62
console.log(ALPHABET[62]); // undefined
console.log('' + ALPHABET[62]); // 'undefined'
There is no character at position 62, so you get undefined. Added to a string, it becomes the nine letters 'undefined', quietly stuck in the middle of your id. Math.floor never does this.
Step 4: make the randomness a parameter
How do you test a function whose answer changes every time? Pass the random source in as a parameter, with Math.random as the default. Normal callers pass nothing. A test passes a function that returns a known number:
function randomId(length, chars = ALPHABET, random = Math.random) {
let out = '';
for (let i = 0; i < length; i++) out += chars[Math.floor(random() * chars.length)];
return out;
}
console.log(randomId(1, 'abc', () => 0)); // 'a'
console.log(randomId(1, 'abc', () => 0.5)); // 'b'
console.log(randomId(1, 'abc', () => 0.99)); // 'c'
console.log(randomId(5, 'x')); // 'xxxxx'
() => 0.5 is a tiny function that always returns 0.5, standing in for Math.random. Now the result is predictable, so you can check it exactly. The chars parameter lets callers choose their own characters, like '0123456789' for a code made only of digits.
Step 5: refuse bad input
A length of -1 or 2.5 makes no sense, and an empty character list leaves nothing to pick from. The answer throws a RangeError, the built-in error for "this value is outside what is allowed", at the top of randomId:
function check(length, chars) {
if (!Number.isInteger(length) || length < 0) throw new RangeError('length must be a whole number, 0 or above');
if (chars.length === 0) throw new RangeError('need at least one character to choose from');
return 'ok';
}
try { check(-1, 'abc'); } catch (e) { console.log(e.message); } // 'length must be a whole number, 0 or above'
try { check(5, ''); } catch (e) { console.log(e.name); } // 'RangeError'
try...catch catches the error so the program can carry on and print it.
Step 6: when Math.random isn't enough
Math.random is fast, but it is not secure. Its numbers come from a formula, and with enough samples someone can predict the next ones. That is fine for an element id or a cache key. It is not fine for a password reset link, a session token or anything an attacker gains by guessing.
For those, use crypto.getRandomValues, which fills an array with unpredictable bytes and works in browsers and in Node:
const bytes = new Uint8Array(4);
crypto.getRandomValues(bytes);
console.log(bytes.length); // 4
console.log(bytes.every((b) => b >= 0 && b <= 255)); // true
A byte is a whole number from 0 to 255. The answer's secureId turns each byte into a character with chars[b % chars.length]. If you only need a unique id and don't mind its format, crypto.randomUUID() gives a standard one.
The full solution
The panel has randomId with its checks and the secure secureId. It prints an id from a fixed sequence twice (the same both times), a truly random id, a secure one and a digits-only one, then the Math.round versus Math.floor comparison. Press Run a few times and watch which lines change.
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
// random is a parameter with a default: the page gets real randomness, a test
// supplies a sequence it controls.
function randomId(length, chars = ALPHABET, random = Math.random) {
if (!Number.isInteger(length) || length < 0) throw new RangeError('length must be a whole number, 0 or above');
if (chars.length === 0) throw new RangeError('need at least one character to choose from');
let out = '';
for (let i = 0; i < length; i++) out += chars[Math.floor(random() * chars.length)];
return out;
}
// For anything security-related. Available in browsers and in Node.
function secureId(length, chars = ALPHABET) {
const bytes = new Uint8Array(length);
crypto.getRandomValues(bytes);
// The modulo introduces a slight bias unless chars.length divides 256. Noted,
// not hidden: for an id it is immaterial, for a key it would not be.
return [...bytes].map((b) => chars[b % chars.length]).join('');
}
// A fixed sequence stands in for randomness.
let i = 0;
const fixed = () => [0, 0.5, 0.99][i++ % 3];
console.log('with a fixed sequence:', randomId(6, ALPHABET, fixed));
console.log('again, same sequence :', (() => { i = 0; return randomId(6, ALPHABET, fixed); })());
console.log('really random :', randomId(10));
console.log('secure :', secureId(10));
console.log('digits only :', randomId(8, '0123456789'));
console.log('--- floor, not round ---');
console.log('Math.round(0.995 * 62) =', Math.round(0.995 * 62), '<- index 62 of 62 does not exist');
console.log('Math.floor(0.995 * 62) =', Math.floor(0.995 * 62), '<- always in range');
Output
21 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 21 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the length is respected', randomId(10).length, 10);
test('a length of 0 gives an empty string', randomId(0), '');
test('every character comes from the alphabet', [...randomId(200)].every((c) => ALPHABET.includes(c)), true);
test('a custom character list is used', [...randomId(50, '0123456789')].every((c) => '0123456789'.includes(c)), true);
test('a one-character list repeats it', randomId(5, 'x'), 'xxxxx');
test('a fixed sequence gives a predictable result', (() => { i = 0; return randomId(3, 'abc', fixed); })(), 'abc');
test('and repeats exactly', (() => { i = 0; const a = randomId(4, 'abc', fixed); i = 0; const b = randomId(4, 'abc', fixed); return a === b; })(), true);
test('0 picks the first character', randomId(1, 'abc', () => 0), 'a');
test('0.5 picks the middle', randomId(1, 'abc', () => 0.5), 'b');
test('0.99 picks the last', randomId(1, 'abc', () => 0.99), 'c');
test('floor keeps the index in range', Math.floor(0.999999 * 62), 61);
test('round would go past the end', Math.round(0.995 * 62), 62);
test('while floor stays inside it', Math.floor(0.995 * 62), 61);
test('and that character does not exist', ALPHABET[62], undefined);
test('a negative length is refused', (() => { try { randomId(-1); return 'no error'; } catch (e) { return e.constructor.name; } })(), 'RangeError');
test('a fractional length is refused', (() => { try { randomId(2.5); return 'no error'; } catch (e) { return e.constructor.name; } })(), 'RangeError');
test('an empty character list is refused', (() => { try { randomId(5, ''); return 'no error'; } catch (e) { return e.constructor.name; } })(), 'RangeError');
test('two calls almost never match', randomId(20) === randomId(20), false);
test('the secure version has the right length', secureId(16).length, 16);
test('and uses the alphabet too', [...secureId(100)].every((c) => ALPHABET.includes(c)), true);
test('62 characters is under 256, so the byte modulo is slightly biased', 256 % ALPHABET.length !== 0, true);
Injecting random as a parameter is the technique that makes randomness testable: the page passes nothing and gets Math.random, and the assertions pass () => 0.5 and check an exact result. Without it you can only assert vague properties.
Math.floor, never Math.round: with 62 characters, round(0.99 * 62) is 62 and ALPHABET[62] is undefined, which the assertions pin down. That off-by-one silently puts "undefined" in the middle of your id.
The important caveat is that Math.random is not cryptographically secure — it is fast, seeded, and its output is predictable given enough samples. Fine for a DOM element id or a cache key. Not fine for a session token, a password reset link, or anything an attacker benefits from guessing; use crypto.getRandomValues, or crypto.randomUUID() if a UUID will do. The b % chars.length bias is noted in the comment rather than hidden: with 62 characters and 256 byte values it is real but immaterial for an id, and for key material you would reject out-of-range bytes instead.
Common mistakes
- Using
Math.roundinstead ofMath.floor. It can pick a position one past the end, putting'undefined'into your id. - Using
Math.randomfor security. Its output can be predicted. Usecrypto.getRandomValuesorcrypto.randomUUID(). - Hard-coding
Math.randominside the function. You can't test exact results. Take the random source as a parameter with a default.
Try it yourself
- Use
randomId(6, '0123456789')to make a six-digit code. - Write a fake random source that returns
0,0.5and0.99in turn, and use it to get'abc'fromrandomId(3, 'abc', fake). - Leave out easily confused characters such as
0,O,1andlfrom the alphabet, and check the length of the new one.