DEV Community

Discussion on: Generating random color with single line of js code

Collapse
 
emmiep profile image
Emmie Päivärinta

I think there's a bug so you'll only get the colors #000000 - #FFFFFE, never #FFFFFF. Because the max value Math.random can return is 0.999… and not 1.0, Math.random() multiplied with some integer n will always be less than n, and rounded down you'll get 0…n-1, not 0…n. For instance Math.floor(Math.random()) will always be 0 because Math.floor(0.999…) is still 0, and Math.floor(Math.random() * 10) will never be 10, because Math.floor(9.999…) is 9.

If you want every possible color you should probably use Math.floor(Math.random()*16777216) (or Math.floor(Math.random()*0x1000000) which I think is more readable).