How to generate random color with JavaScript

Today we gonna learn how to generate a random color using JavaScript with a few lines :

1-Generate random integer between 0 and 15

first we need to know how to get a random number

let randomNumber = Math.random();
//return random number between 0 and 1 (0.46578483)

but we don’t want this result, we need random number integer between 0 and 15
To have it we have use you Math.floor()

let randomNumber = Math.floor(Math.random()*15);
//return random integer between 0 and 15

2-Why 0 and 15 ?

Well this is the length of an array that contains all alphanumeric of HEX code, and we want to select random index 6 times and join all in one string.
( In this example we will use the HEX code, 0 to 9 and a to f
Ex: #E06910 , #02198C, #BADA55)

const hexArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];

3-Get random HEX code

we need to loop 6 times and concatenate the result every time to the code string

let code = "";
for(let i=0; i<6; i++){
 code += hexArray[Math.floor(Math.random()*15)];
}
//don' forget the code start with "#"
code = `#${code}`;

4-Make your code inside function

now we need to write our code in function to use it perfectly

function generateColor(){
 const hexArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
 let code = "";
 for(let i=0; i<6; i++){
  code += hexArray[Math.floor(Math.random()*15)];
 }
 return `#${code}`
}

In this example I use it in the body background:

document.body.style.backgroundColor = generateColor();

live demo :

Thanks for reading

I hope you find that useful, if you want to practice more you can create your own function to generate random RGB or HSL color .

17