Skip to content

Generate a random color in JavaScript

To get a random hex color in JavaScript, multiple a random value to the decimal color value 16777215 and convert it to hexadecimal value.

Math.floor(Math.random()*16777215).toString(16);
//6c02b6
Math.floor(Math.random()*16777215).toString(16);
//6e22e2
Math.floor(Math.random()*16777215).toString(16);
//deae9a
Math.floor(Math.random()*16777215).toString(16);
//314e66
Math.floor(Math.random()*16777215).toString(16);
//b5485e
Advertisements

Extract this to a function and prefix # to it.

function getRandomColor() {
	return Math.floor(Math.random()*16777215).toString(16);
}


console.log("#" + getRandomColor());
// #b08ea3
console.log("#" + getRandomColor());
// #d2fbd2
console.log("#" + getRandomColor());
// #227e6c
See also  HackerRank Solutions - DP - Coin Change - Java Solution
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.