crypto.randomInt Draws Bounded Integers
Draw bounded integers with crypto.randomInt, where the upper bound is exclusive, avoiding the modulo bias that hand-rolled Math.random tricks introduce.
Code
import { randomInt } from 'node:crypto';
// randomInt(max) draws from [0, max); with two bounds the upper one is excluded
const dice = randomInt(1, 7); // [1, 7) -> 1..6
console.log('dice in range:', dice >= 1 && dice <= 6);
// Range holds across many draws
let inBounds = true;
for (let i = 0; i < 1000; i++) {
const value = randomInt(10, 20);
if (value < 10 || value >= 20) inBounds = false;
}
console.log('1000 draws all in [10, 20):', inBounds);
// small ranges collect every face quickly without modulo bias
const seen = new Set();
while (seen.size < 6) seen.add(randomInt(1, 7));
console.log('collected all six faces:', seen.size === 6);Output
Captured from a sandboxed run of this snippet in the build pipeline.
dice in range: true
1000 draws all in [10, 20): true
collected all six faces: trueInside the snippet
The nesting pairs for (let i = 0; i < 1000; i++) with while (seen.size < 6) seen.add(randomInt(1, 7)); — the inner runs once per outer step. randomInt comes from node:crypto — Node.js core modules the runtime ships with.
Every operation runs against top-level bindings: dice, inBounds, seen.
Points of care
- The dependency surface is just
node:crypto, and that one is built into Node.js. - A browser is the runtime here:
cryptoare not available in Node.
Using it
The demo output is labeled (dice in range:, 1000 draws all in [10, 20):, collected all six faces:), so each printed line points back to the operation that produced it.
Key statements
const seen = new Set();
Interactive Tools for This Topic
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.Password GeneratorGenerate random passwords from selectable character classes using crypto.getRandomValues with rejection sampling and class guarantees.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- What does this import from outside the project?
- Only `node:crypto`, and that is a Node.js built-in — it comes with the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.