Generate Random Hex Color in JavaScript

- 1 minute read

This handy JavaScript function will generate a random hex color, using the built-in Math.random method:

const generateColor = () => {
    return `#${(Math.random() * 0xfffff * 1000000).toString(16).slice(0, 6)}`;
};

Here is an example output: #a3b4dc.

This format is directly compatible with CSS and other languages.

This function will not shorten six-character strings to three-character strings when possible. For example, #00ff00 wouldn’t be shortened to #0f0. All outputs will be six characters preceded by a hash symbol.

Link to this section One-line color generator

And here is a one-liner variant of the generateColor() function, with the exact same behavior:

const generateColor = () => `#${(Math.random() * 0xfffff * 1000000).toString(16).slice(0, 6)}`;

Link to this section Conclusion

I’ve found this function to be especially useful when working at the intersection of JavaScript and CSS.

Thanks for reading!