Reference article · Programming
Random values in JavaScript
JavaScript provides different ways to obtain random values. Choose according to how the result will be used.
Math.random()
Math.random() returns a pseudorandom number at least zero and less than one. It suits simple simulations and visual effects, but is not cryptographically secure. Do not use it for session tokens, recovery codes or attacker-resistant decisions.
Integers in a range
Multiply by an exclusive upper limit and apply Math.floor. This selects an index in a nonempty array. Math.round would give differently sized intervals to the endpoints.
const options = ["HTML", "CSS", "JavaScript"]; const index = Math.floor(Math.random() * options.length); console.log(options[index]);
Web Crypto
crypto.getRandomValues() fills an integer array with cryptographically secure values. Unlike randomUUID(), it can also run in an insecure context.
Example
The call modifies the supplied array. This obtains four 32-bit integers; it is not a complete password generator.
const values = new Uint32Array(4); crypto.getRandomValues(values);
Distribution and bias
Secure generation does not make every transformation uniformly distributed. Using % when the target range does not divide the source range exactly can introduce bias. Sensitive draws or protocols need a reviewed generation, selection and verification process.
What to check
- Run selection repeatedly; every result must belong to the list.
- Check the exclusive upper limit and handle empty lists first.
- Do not expect identical results or treat a small sample as statistical proof.
References
Related articles
- Fundamentals: variables, conditions and loops
- Semantic HTML and page structure
- CSS: box model, Flexbox and Grid
- JavaScript: functions, parameters and scope
- JavaScript: arrays, objects and data transformations
- DOM and events: connect JavaScript to HTML
- Promises, async/await and fetch requests
- HTTP and web APIs: requests, responses and status codes
- JSON: format, parsing and data validation
- Git: changes, commits, branches and remotes
- Node.js and npm: project scripts and dependencies
- Debugging and tests: finding and checking errors
- Colour formats: HEX, RGB and HSL
- UUID identifiers
