HowTo: Generate Random Color Values In JavaScript [Hex, RGB, HSL]

Colors are an essential piece of engineering enchanting aesthetics. Hence this post with code snippets to provide an insight on how to generate random colors in JavaScript. We are going to discuss the process of generating random color values in the following formats:

The code below is written in ES6 specification of JavaScript.

Hex

The Hex format, which also happens to be the most widely used format to represent color on the World Wide Web, consists of a ** # ** followed by six hexadecimal values. The following function returns a random color value in Hex format:

function getRandomColorHex() {
    const colorLetters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += colorLetters[Math.floor(Math.random() * 16)];
    }
    return color;
}

RGB

RGB is an easy to use format in which the color value is represented by the format rgb(R, G, B), where R, G, B are intensities of Red, Green and Blue respectively with their values ranging from 0 to 255. A value of 0 represents the minimum intensity of color and a value of 255 represents the maximum intensity of color. When the intensity of all three colors is 0 it creates black color and when all colors are set to their brightest which is 255 it creates white color. The function below returns a random color value in RGB format:

function getRandomColorRgb() {
	let red = Math.floor(Math.random() * 256);
	let green = Math.floor(Math.random() * 256);
	let blue = Math.floor(Math.random() * 256);
	return `rgb(${red}, ${green}, ${blue})`;
}

HSL

The format of representating color in HSL is hsl(H, S, L), where H, S and L are Hue, Saturation and Lightness respectively. The hue of color can be any value between 0 and 360 while the saturation and lightness are in percentage and their vale can be anything from 0 to 100. The function below returns a random color value in HSL format:

function getRandomColorHsl() {
	let hue = Math.floor(Math.random() * 360);
	let saturation = Math.floor(Math.random() * 100);
	let lightness = Math.floor(Math.random() * 100);
	return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
}

Random colors can be utilized in various ways. For an example check out this Gradient Generator I created which creates gradients with randomly generated colors. Any further queries and suggestions are welcome in the comments section below.

Show Comments