Randomize color by number in JavaScript


We are required to write a function that returns a random hex color. So here is the code for doing so −

Example

const generateRandomColor = () => {
   const keys = '0123456789ABCDEF';
   let color = '';
   while(color.length < 6){
      const random = Math.floor(Math.random() * 16);
      color += keys[random];
   };
   return `#${color}`;
};
console.log(generateRandomColor());
console.log(generateRandomColor());
console.log(generateRandomColor());
console.log(generateRandomColor());

Output

The output in the console will be −

#C83343
#D9AAF3
#9D55CC
#28AE22

Updated on: 20-Aug-2020

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements