Randomize color by number in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 20-Aug-2020 06:27:04
Advertisements