Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Generate A Random Hex Color In JavaScript

This code generates a random hex color value (including the `#` sign)

Code

const randomHex = () => {
    const number = Math.floor(Math.random() * 16777215)
    const string = `#${number.toString(16).padStart(6, '0')}`
    return string 
}

console.log(randomHex())

Results

#580e8b

This is based off of the code on [[https://css-tricks.com/snippets/javascript/random-hex-color/][this page]] but adds `padStart` so that colors that would otherwise be less than six characters are padded properly.

There are other approaches on the page as well if you're interested.