DEV Community

Discussion on: Random colour with JavaScript

Collapse
 
savagepixie profile image
SavagePixie

Great explanation, but that method can generate hexadecimal numbers with less than six digits, so you might want to pad the start with zeroes.

Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')
Collapse
 
telmo profile image
Telmo Goncalves

Thanks for that 🙏

Collapse
 
lexlohr profile image
Alex Lohr

You could also use (16777216 * (1 + Math.random()) | 0).toString(16).slice(1).