DEV Community

Cover image for Two ways to generate random color - Daily JavaScript #5
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

Two ways to generate random color - Daily JavaScript #5

Why not make your own color generator 🌈?

Method 1 - Long method

// Generate random color in hex format
const randomColor = () => {
    const letters = "0123456789ABCDEF";
    let color = "#";
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
Enter fullscreen mode Exit fullscreen mode

Method 2 - Short and Best Method

const randomColor = Math.floor(Math.random()*16777215).toString(16);
console.log("#" + randomColor)
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, have a nice day!

Top comments (1)

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Interesting that so many random color solutions suffer from the same off-by-one error (I left the same comment on the post Our favorite javascript one-liners):

const randomColor = Math.floor(Math.random()*16777215).toString(16);

16777215 == 0xffffff, which is the max "value" for a hex color; however, Math.floor(Math.random() * n) gives integers in the range 0..(n - 1), not 0..n. For example, Math.floor(Math.random() * 2) will always give 0 or 1, never 2.

If you want to have the possibility of ever generating pure white (0xffffff), you instead need to use a multiplier of 0xffffff + 1:

const randomColor = Math.floor(Math.random() * 0x1000000).toString(16);
// equivalent to...
const randomColor = Math.floor(Math.random() * (0xffffff + 1)).toString(16);
// equivalent to...
const randomColor = Math.floor(Math.random() * 16777216).toString(16);
Enter fullscreen mode Exit fullscreen mode