DEV Community


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

letsbsocial1 profile image
Maria Campbell

I discovered this too, and it's great. However, occasionally it generates a hex code that contains only 5 characters instead of 6. But if you chain ES6's .padStart() method to the end of the code like so:

const randomColor = Math.floor(Math.random()*16777215).toString(16).padStart(6, '0')
Enter fullscreen mode Exit fullscreen mode

This ensures that a 6 character hex color code is always generated. Thanks for the explanation about the number 16777215. I was wondering about that part!

This is where I learned about using ES6's padStart() method to fix the hex color code length issue: