Generate a random hex color
Return a #rrggbb color from 24 random bits.
function randomColor() { return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0')}`; }
Usage
/^#[0-9a-f]{6}$/.test(randomColor()); // → true
Array.from({ length: 1000 }, randomColor).every(color => color.length === 7); // → true
Know the limits
- The original’s second version omitted padStart, so colors below #100000 came out with fewer than six digits.
- Random colors ignore contrast: check text against WCAG’s 4.5:1 ratio before using one as a background.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Generate a random hex color from the original 1loc collection by Nguyen Huu Phuoc, with robinpokorny. Copyright (c) 2020 phuoc-ng. MIT licensed.
Pads to six digits; the original's second version could return shorter colors. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Generate a random boolean — Return true or false with equal probability.
- Generate a random floating point number in given range — Scale Math.random into [min, max).
- Generate a random integer in given range — Return an integer from min to max, both included.