Cover image for Generating random color with single line of js code

Generating random color with single line of js code

akhil_001 profile image Akhil sai ・2 min read

Did you ever feel bored or tired of writing long random colors for different divs or spans just to test something simple?

So here is a simple solution. The following snippet generates a random color in hexadecimal format.

var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
//generates a random color -> #56eec7

That's it!🥳 You can place this in a function and call the function everytime you need a random color

function generateRandomColor()
    var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
    return randomColor;
    //random color will be freshly served
document.body.style.backgroundColor = generateRandomColor() // -> #e1ac94
someDiv.style.color = generateRandomColor() // -> #34c7aa

Well this is the end of the trick. If you are in hurry, you can the leave post here.


if you are curious to know why only the number 16777215 and toString(16) are used, then the following part covers those explanations

So, let's divide the code into 3 parts

1.Why the number 16777215?

  • Well this needs a little bit of Math. We all know that the colors range from #000000(pitch black) to #ffffff(pure white).
  • The number of colors that exist from black to white as per rgb values are 16777216.
  • This can be calculated simply by using permutation&combination formula [result = m to the power of n => 16 to power of 6 => 16777216]
  • However our ultimate goal is to convert the number into hexadecimal format and 16777216 converts to 1000000 and 16777215 converts to ffffff. Hence we proceed with 167777215 as the highest number for hexadecimal conversion


  • As we need some randomness in our output we are multiplying our magic number with Math.random() which returns floating number in range from inclusive of 0 to exclusive of 1
  • As seen the output is floating point and we need to cut down it to an integer for hex conversion and hence we use Math.floor() for that

3.Hexadecimal conversion

  • Now we are in the endgame, the last part of the code. To convert a number to hexadecimal format string , we have a beautiful method toString() which accepts the number that tells to which format it has to convert.
  • As we are converting to string of hexa-decimal format and hence we pass 16 as the argument as follows
- All we need to now is just attach # before the string
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);

That's it!
Kudos to you!
You have successfully completed the post
Happy C0ding!


Editor guide