Random hex color code

OSCC · JavaScript, Math, Random · Jan 7, 2021

Generates a random hexadecimal color code.

const randomHexColorCode = () => {
  let n = (Math.random() * 0xfffff * 1000000).toString(16);
  return '#' + n.slice(0, 6);
};
randomHexColorCode(); // '#e34155'

Recommended snippets & collections

  • Working with color in JavaScript requires some understanding of color formats and conversions. Luckily, this snippet collection's got you covered.

  • RGB to hex

    JavaScript, String

    Converts the values of RGB components to a hexadecimal color code.

  • Generates an array of n random integers in the specified range.

  • Random integer in range

    JavaScript, Math

    Generates a random integer in the specified range.