Generates a random hexadecimal color code.
- Use Math.random() to generate a random 24-bit (6 * 4bits) hexadecimal number.
- Use bit shifting, and after that use Number.prototype.toString to transform it to a hexadecimal string ().
const randomHexColorCode = () => {
let number = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + number.slice(0, 6);
};
randomHexColorCode(); // '#e34155'
Top comments (1)
Nice, though I am not sure I'd call that variable
number
. After all it is astring
.