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.
Yeah someone else pointed this out to me. Math.floor vs Math.round is one of those things I always forget. Also, excellent work on the alt method! Just as a note, with that solution, it is possible you will get hex codes that are less than 6 digits in length, which won't work as color codes. You'll still need a way to check for the length of the code.
Log in to continue
We're a place where coders share, stay up-to-date and grow their careers.
Hi, I just wanted to point out small bug.
should use
Math.floor
instead ofMath.round
.Also I wrote different approach to generate random hex. There is no need for loops.
Your code is shorter but harder to understand.
How? You generate random number and convert it to string of number with base 16.
The same approach is in the article, but uses 6 random number instead of one number.
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.
Fair point, easy fix
or more readable
//edit: Btw, because of your use of
Math.round
values don't have the same probability distributionYeah someone else pointed this out to me. Math.floor vs Math.round is one of those things I always forget. Also, excellent work on the alt method! Just as a note, with that solution, it is possible you will get hex codes that are less than 6 digits in length, which won't work as color codes. You'll still need a way to check for the length of the code.