# Generate a random hex color

Return a #rrggbb color from 24 random bits.

Canonical: https://1loc.dev/random/generate-a-random-hex-color/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Usage lines executed in Node.js 22 and headless Chromium; no external services
Updated: 2026-10-28

## Implementation

```javascript
function randomColor() { return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0')}`; }
```

## Usage

```javascript
/^#[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.

## 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 does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/generate-a-random-hex-color.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: robinpokorny
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: 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.
