EN
TypeScript - generate random hex color
0
points
In this article, we would like to show you how to generate random hex colors using TypeScript.
Quick solution:
const randomColor = (): string => {
let result = '';
for (let i = 0; i < 6; ++i) {
const value = Math.floor(16 * Math.random());
result += value.toString(16);
}
return '#' + result;
};
Practical example
In this example, you can see generated color code in hex with preview.
const randomColor = (): string => {
let result = '';
for (let i = 0; i < 6; ++i) {
const value = Math.floor(16 * Math.random());
result += value.toString(16);
}
return '#' + result;
};
// Usage example:
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
Example output:
#d5af2c
#396391
#01b8a7
Alternative solutions
1. The below solution uses predefined digits that compose hex color.
const DIGITS: string = '0123456789ABCDEF';
const randomColor = (): string => {
let result = '';
for (let i = 0; i < 6; ++i) {
const index = Math.floor(16 * Math.random());
result += DIGITS[index];
}
return '#' + result;
};
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
Example output:
#CCAD03
#15123A
#EBDE9B
2. One random number solution
const randomColor = (): string => {
const dec = Math.floor(0x1000000 * Math.random()); // 0x1000000 = 0xFFFFFF + 1
let hex = dec.toString(16);
for (let i = hex.length; i < 6; ++i) {
hex = '0' + hex;
}
return '#' + hex;
};
console.log(randomColor()); // #c68362
console.log(randomColor()); // #1c4bcc
console.log(randomColor()); // #4c2be3
Output:
#c68362
#1c4bcc
#4c2be3