DEV Community

loading...

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

Collapse
beerwerd profile image
Beerwerd

Your code is shorter but harder to understand.

Collapse
lukaszahradnik profile image
Lukáš Zahradník

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.

Thread Thread
thecodepixi profile image
Emily A. Pixi Author

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.

Thread Thread
lukaszahradnik profile image
Lukáš Zahradník

Fair point, easy fix

const generateHex = () => `#${Math.floor(Math.random() * 256**3).toString(16).padStart(6, '0')}`

or more readable

const generateHex = () => {
  const hex = Math.floor(Math.random() * 256**3).toString(16).padStart(6, '0')
  return `#${hex}`
}

//edit: Btw, because of your use of Math.round values don't have the same probability distribution