Languages
[Edit]
EN

TypeScript - generate random hex color

0 points
Created by:
Imaan-Morin
1009

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

See also

  1. JavaScript - generate random hex color
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join