Computer >> Computer tutorials >  >> Programming >> Javascript

Generating random hex color in JavaScript


We are required to write a JavaScript function randomColor that returns a randomly generated hex color every time it is called.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const randomColor = () => {
   let color = '#';
   for (let i = 0; i < 6; i++){
      const random = Math.random();
      const bit = (random * 16) | 0;
      color += (bit).toString(16);
   };
   return color;
};
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());

Output

The output in the console will be −

#762b46
#cfa0bf
#a20ee1
#c2f7e0
#5d5822
#380f30
#805408