## DEV Community

Ahmed Zougari

Posted on • Updated on

# 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()*16);
//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

``````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()*16)];
}
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()*16)];
}
return `#\${code}`
}
``````

In this example I use it in the body background:

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

live demo :