10
3
This blog post about generating random CSS color codes in JavaScript have multiple solutions for generating a random color in JavaScript. The shortest I can find is this:
'#'+(Math.random()*0xffffff).toString(16).slice(-6)
If you are not familiar with CSS color code read documentations here.
Can we do better? What about other languages?
Yours is broken, you're missing a
+
after the'#'
– Doorknob – 2013-09-16T22:29:35.6371You can remove the slice by doing this
#'+(Math.random()*0xffffff|0).toString(16)
– Griffin – 2013-09-17T10:39:19.1831What is the "0xffffff" needed for? I'm not seeing much of a difference in my results without it. – path411 – 2013-09-17T22:18:21.007
4@path411 Theoretically,
Math.random().toString(16)
can produce a representation with less than 6 hex-digits after the (hexa)decimal point, in which case the function would break. For example, 0.1658172607421875 becomes 0.2A73 in hex. – primo – 2013-09-18T08:51:11.067