DEV Community

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

 
thecodepixi profile image
Emmy | Pixi

Just to clarify, in the article, the intention is to generate individual digits and convert them to hex one at a time until you have a string of 6 hexadecimal digits. If you just generate any decimal number between 0 and 16777215 and then convert that number to hexadecimal, it will sometimes output hexadecimal numbers shorter than 6 digits (i tested and got a few 4 and 5 digit results) which cannot be used as a hex color code and will cause the function to break if used to assign a code to an element on the page. You still need a way to check for length of 6 on your output. That said, your code does work a lot of the time. But sometimes it doesn't. For me, it broke about 1/20 times when I tested it.