Javascript function to create hexa color

Learn how to write a javascript function to create a random hexa color.

A Hexa string of length 6 starting with a # represents a Hexa color.

"#31c05f"

A color is composed of three different values R (red), G (green), B (blue) whose digital value ranges from 0-255.

We will also create a random function which will be generating a random number between 0 – 255 and convert it to a hexa string of length two.

To convert the number to the hexa string we will use toString() method.

const randHex = () => {
  return pad(Math.floor(Math.random() * 256).toString(16));
}

We are using another helper function pad which will prefix a 0 if hexa string is of length one.

const pad = (inp) => {
  return String(inp).length == 1 ? '0' + inp : inp;
}

Now to create a hexa color string function we will call the randHex() function thrice and append a "#" to the generated string.

const randHexColor = () => {
  return  '#' + randHex() + randHex() + randHex();
}

Now when we combine all the function it will generate a random Hexa color string.

const pad = (inp) => {
  return String(inp).length == 1 ? '0' + inp : inp;
}

const randHex = () => {
  return pad(Math.floor(Math.random() * 256).toString(16));
}

const randHexColor = () => {
  return  '#' + randHex() + randHex() + randHex();
}

console.log(randHexColor());
//"#31c05f"