Syntax
crypto.getRandomValues(new Uint8Array(16));
crypto.randomUUID();Examples
Cryptographic Random Values: working example
Run this standalone example in a modern browser console unless another environment is specified. Expected result: The console prints 16 32 and true; the actual bytes differ on each run.
const bytes = crypto.getRandomValues(new Uint8Array(16));
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
console.log(bytes.length, hex.length);
console.log(/^[0-9a-f]{32}$/.test(hex));- Expected result: The console prints 16 32 and true; the actual bytes differ on each run.
- Padding gives every byte exactly two hexadecimal characters.
- The test verifies representation length and alphabet, not a particular random result.
Best practices
- Use this API instead of Math.random for security-sensitive randomness.
- Avoid biased modulo mapping when choosing uniformly from a range that does not divide the source range.
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification