DEV Community

Amazing Enyichi Agu
Amazing Enyichi Agu

Posted on

How to Generate random hex color values in javascript

Generating random RGB colors in a javascript web app would be very easy to implement.

We would just have a function with no parameters which would generate a random color from 0 - 255. Something like this:

const digit = () => `${Math.round(Math.random() * 255)}`
Enter fullscreen mode Exit fullscreen mode

and now to generate our colors, we make another function to return an array of three random digits

const array = () => {
  let list = [];
  for (let i = 0; i < 3; i++) {
    list.push(digit());
  }
  return list;
}
array()
//-> [155, 13, 9]
Enter fullscreen mode Exit fullscreen mode

We just pushed three random numbers into the list and returned it. We also made array a function so that it dosen't have a definite value like a variable. whenever we call array(), it runs the whole thing over again and produces a different value every time.

Finally, to get a random rgb color:

const color = (r, g, b) => `rgb(${r}, ${g}, ${b})`;
color(...array())

//-> "rgb(142, 112, 11)"
Enter fullscreen mode Exit fullscreen mode

Notice we had to 'spread' the array that would be returned from the function array(). These syntax are from ES6+ javascript. To learn more about it, checkout Codeacademy.

For hex colors though, we need to

  • Convert the numbers to base 16
  • Make sure we add 0 to the begining of a hex digit whoose length is not up to two

Why we are doing this is because, for example
11 in base 16 is B
14 is E
15 is F

An rgb(11,14,15) and #bef are not the same thing. The hex equivalent should be #0b0e0f. We need to pad our digits with 0.
So lets modify the array to push hex digits that have been converted to base 16 and padded. Well use padStart method for strings.

const array = () => {
  let list = [];
  for (let i = 0; i < 3; i++) {

    //convert to base 16
    let hex = digit().toString(16)

    //check if length is 2, if not pad with 0
    hex = hex.length < 2 ? hex.padStart(2, 0) : hex;

    //push hex
    list.push(hex);
  }
  return list
}
Enter fullscreen mode Exit fullscreen mode

We also modify the color function to return a value in hex format

const color = (r, g, b) => `#${r}${g}${b}`;
Enter fullscreen mode Exit fullscreen mode

finally, if we run color(...array()) a random hex appears.

color(...array)
//-> #efef22
Enter fullscreen mode Exit fullscreen mode

This is my first blog post. Suggestions are highly welcome

Top comments (3)

Collapse
 
savagepixie profile image
SavagePixie

Good explanation and good job and making sure to add zeroes!

One small thing, though, pad functions add stuff to a string until the string reaches the desired length. So the ternary there is unnecessary.

let hex = digit().toString(16)

 //check if length is 2, if not pad with 0
hex = hex.length < 2 ? hex.padStart(2, 0) : hex;

The above code could be rewritten as:

let hex = digit().toString(16)
hex = hex.padStart(2, 0)

Or even:

const hex = digit()
    .toString(16)
    .padStart(2, '0')
Collapse
 
enyichiaagu profile image
Amazing Enyichi Agu

Thank you very much. Never even thought of that.

Collapse
 
namanthanki profile image
Naman Thanki


function generateRandomHexColor() {
return `#${Math.random().toString(16).substring(2, 8)}`;
}


I think you could just do this also