JavaScript

Random Hex Color

by @admin
10h ago
Apr 28, 2026
Public
Generates a random 6-digit hex colour string. Useful for seeding avatar backgrounds, chart series colours, placeholder UI elements, and testing colour-dependent components. The crypto version produces a more unpredictable result suitable for generating unique palette tokens.
JavaScript
// Simple
const randomHex = () =>
  '#' + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0');

// Crypto-quality
const randomHexSecure = () => {
  const bytes = new Uint8Array(3);
  crypto.getRandomValues(bytes);
  return '#' + Array.from(bytes).map((b) => b.toString(16).padStart(2, '0')).join('');
};

// Usage
console.log(randomHex());       // e.g. '#a3f4c1'
console.log(randomHexSecure()); // e.g. '#7b2d9f'
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.