- Instant help with your JavaScript coding problems

Generate random color with JavaScript

How to generate random color with JavaScript?
function getRandomColor() {
    const availableCharacters = '0123456789ABCDEF';
    const availableCharacterLength = availableCharacters.length;

    let color = '#';

    for (let i = 0; i < 6; i++) {
      color += availableCharacters[Math.floor(Math.random() * availableCharacterLength)];

    return color;

console.log(getRandomColor()); // #3BB46D

To generate a random color in JavaScript is very similar to generating a random string. You can use the Math.random function with a limited character set and with a fixed length. As colors can be described with 6 characters where only numbers from 0..9 and letters from A..F are allowed. So the function that generates random color simply randomly selected a character from the '0123456789ABCDEF' string 6 times in a row and concatenate the letters into a string that is prefixed with the character '#' .

Share "How to generate random color with JavaScript?"