Trusted answers to developer questions

How to generate a random color in JavaScript

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

A hexadecimal color can be represented as #RRGGBB:

  • RR — red
  • GG — green
  • BB — blue

The value of the Hexadecimal can range from 00 to FF. So, the maximum value can be FFFFFF - white color, and the minimum value can be 000000 - black color.

In JavaScript, we add 0x before a hexadecimal number:

let testHexVal = 0xff; // 255
let maxColorVal = 0xFFFFFF; // 16777215

Let’s create a random number from this maxVal:

let maxVal = 0xFFFFFF; // 16777215
let randomNumber = Math.random() * maxVal;  // returns a floating point random number 

// convert the floating-point number to an integer 
randomNumber = Math.floor(randomNumber);

Now, that we have a random number generated for the hex, let’s convert that integer into hex again using the toString(16) method:

let maxVal = 0xFFFFFF; // 16777215
let randomNumber = Math.random() * maxVal; 
randomNumber = Math.floor(randomNumber);
let randColor = randomNumber.toString(16);

The code above will generate a random color; but, there may be a chance that the string length will be less than 6. In that case, we can use padStart or padEnd to ensure that the string length is at least 6. If the string length is less than 6, the padStart/padEnd will add the filler values we passed to the function:

let maxVal = 0xFFFFFF; // 16777215
let randomNumber = Math.random() * maxVal; 
randomNumber = Math.floor(randomNumber);
randomNumber = randomNumber.toString(16);
let randColor = randomNumber.padStart(6, 0);   

Imagine that the generated randomNumber is 123b, and the length of 123b is less than 6. In this case, the padStart method will add 0 to the beginning of the randomNumber until length becomes 6. The randColor will be 00123b

The complete function to generate a random color is:

function generateRandomColor(){
let maxVal = 0xFFFFFF; // 16777215
let randomNumber = Math.random() * maxVal;
randomNumber = Math.floor(randomNumber);
randomNumber = randomNumber.toString(16);
let randColor = randomNumber.padStart(6, 0);
return `#${randColor.toUpperCase()}`
}
console.log(generateRandomColor());

Another way to write the above function is:

const randColor = () => {
return "#" + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0').toUpperCase();
}
console.log(randColor());

RELATED TAGS

javascript
random color
Did you find this helpful?