JavaScript Snippet

Random Integer in a Range

Difficulty: Easy

Off-by-one bugs in random integer helpers are the silent kind: tests pass, distributions look right, but the maximum value never appears. This snippet covers the inclusive `[min, max]` form most people actually want, the unbiased version using `crypto.getRandomValues`, and a helper for picking a uniform random element from an array. Use it for sampling, dice rolls, jitter, and quick demos.

Code Snippets
/

Random Integer in a Range

Random Integer in a Range

Off-by-one bugs in random integer helpers are the silent kind: tests pass, distributions look right, but the maximum value never appears. This snippet covers the inclusive `[min, max]` form most people actually want, the unbiased version using `crypto.getRandomValues`, and a helper for picking a uniform random element from an array. Use it for sampling, dice rolls, jitter, and quick demos.

JavaScript
Easy
3 snippets
math
randomized-algorithms
utility

195 views

6

The classic Math.floor(Math.random() * (hi - lo + 1)) + lo is inclusive on both ends; the + 1 is the part beginners often forget, which silently drops the upper bound from the distribution. Math.ceil(min) and Math.floor(max) normalise non-integer inputs so a caller passing 1.5, 6.5 still draws from {2, 3, 4, 5, 6}. The swap guards against min > max so the function does not silently return only min. Use this for any non-cryptographic case (UI demos, retry jitter, sampling).