a shot of dev knowledge

RELATED TAGS

# How to generate a random color in JavaScript

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);


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);
return #\${randColor.toUpperCase()}
}
console.log(generateRandomColor()); 

Another way to write the above function is:

const randColor = () =>  {
}

console.log(randColor());

RELATED TAGS

RELATED COURSES
View all Courses
Related Courses
RELATED COURSES
View all Courses
Keep Exploring

Learn in-demand tech skills in half the time