Snippet: Generating random HEX color

May 06, 2024


In several projects, I had to create functionality related to the generation of a random color. To do it it’s good to know how the color in hexadecimal format is composed. Usually it’s represented by 3-byte (4 is also possible) number. Each byte represent the red, green and blue parts of the color. Each part of the digit is ranging from 00 to FF.

If the hex has also the fourth byte it represents the alpha channel, useful for defining an opacity. In this example I omitted the 4th byte.

function generateHex() {
  const possibleCharacters = [

  const randomIdx = () =>
	  Math.floor(Math.random() * (possibleCharacters.length - 1));
  const colorHex = () =>

  return `#${colorHex()}${colorHex()}${colorHex()}`;