DEV Community

Discussion on: What the Hex!? (how to generate random hex color codes in javascript)

Collapse
 
khauri profile image
Khauri • Edited

Nice work! I love seeing the thought processes behind figuring out how to make code better. It's like watching someone piece together a mystery in front of you.

I'm sure you know this as well, but for anyone who doesn't, if you prefix a number with 0x you can use hex values in your code. (There's also 0b for binary and 0o for octal).

Something else to note is that when using Math.floor1 since Math.random generates a random number between 0 and 1, but never exactly 1, you have to add 1 to your maximum or else it will never generate that value. So in this case, you should go up to 16 or you'll never get the value f:

Math.floor(Math.random() * 16)
// or 
Math.floor(Math.random() * 0x10)

1 I didn't read the article well enough and assumed Math.floor was being used

Collapse
 
thecodepixi profile image
Emmy | Pixi

Thanks, Khauri! I actually didn't know about the 0x thing. That's super cool! And ++ to the Math.floor() point. It's one of those things I always forget. I used Math.round() in its place but do know that that's not the best solution.