Generate a random hex color

Return a #rrggbb color from 24 random bits.

JavaScriptNode.js & browsers Version 1.0.0 · MIT · .md

generate-a-random-hex-color.js
function randomColor() { return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0')}`; }

Usage

usage.js
/^#[0-9a-f]{6}$/.test(randomColor()); // → true
Array.from({ length: 1000 }, randomColor).every(color => color.length === 7); // → true

Lines marked → were executed in Node.js 22 and in headless Chromium, and each result was compared with the value shown. Lines marked e.g. are illustrative.

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.

Usage lines executed in Node.js 22 and headless Chromium; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.