DEV Community

Cover image for Random Hex Color Code Generator
Christopher Glikpo  ⭐
Christopher Glikpo ⭐

Posted on

Random Hex Color Code Generator

Generates a random hexadecimal color code.

  • Use Math.random() to generate a random 24-bit (6 * 4bits) hexadecimal number.
  • Use bit shifting, and after that use Number.prototype.toString to transform it to a hexadecimal string ().
const randomHexColorCode = () => {
  let number = (Math.random() * 0xfffff * 1000000).toString(16);
  return '#' + number.slice(0, 6);
};

randomHexColorCode(); // '#e34155'
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
szabgab profile image
Gabor Szabo

Nice, though I am not sure I'd call that variable number. After all it is a string.