DEV Community

Discussion on: Two ways to generate random color - Daily JavaScript #5

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