JavaScript random color generator

Post shows how to generate random color in hexadecimal notation using JavaScript. Simple task is explained through several examples and working demo. Click on “Demo” button and see how rndColor() function generates colors (for demo purpose, rndColor() is called 6 times).

1. Classical example with array
Nothing special. Hexadecimal digits are defined in array. In each loop iteration, code generates random number in range 0 – 15 and concatenates digits from array to the final color string.

function rndColor() {
    var hex = ['0', '1', '2', '3', '4', '5', '6', '7',
               '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'],
        color = '#', i;
    for (i = 0; i < 6 ; i++) {
        color = color + hex[Math.floor(Math.random() * 16)];
    }
    return color;
}

2. Hexadecimal digits in string
Here is small modification of previous example using split() method. split() method splits a string into an array of substrings, and returns the new array (like explicit array definition in first example).

function rndColor() {
    var hex = '0123456789ABCDEF'.split(''),
        color = '#', i;
    for (i = 0; i < 6 ; i++) {
        color = color + hex[Math.floor(Math.random() * 16)];
    }
    return color;
}

3. Generating each color component separatly
Each color component is generated separately. Randomly generated number (in range 0 – 255) is converted to hexadecimal format with toString(16) method. And finally, concatenation with ‘0’ and substr(-2) will take care of leading zeros. IE8 will have a problem with negative index in substr method. In that case slice may be used instead.

function rndColor() {
    var r = ('0' + Math.floor(Math.random() * 256).toString(16)).substr(-2), // red
        g = ('0' + Math.floor(Math.random() * 256).toString(16)).substr(-2), // green
        b = ('0' + Math.floor(Math.random() * 256).toString(16)).substr(-2); // blue
    return '#' + r + g + b;
}

4. Example with nested function
Modification of previous example using nested function instead of repeating code for RGB color components.

function rndColor() {
    function c() {
        return ('0' + Math.floor(Math.random() * 256).toString(16)).substr(-2);
    }
    return '#' + c() + c() + c();
}

5. Shortest example
Script generates random number in range 0 – 16777215 (0x000000 – 0xFFFFFF). Actually, Math.random() generates a decimal number from 0 to slightly less than 1 (shown as <1). Multiplying has greater precedence then bitwise operation, so random number will be multiplied first and then shifted left. Shifting left for 0 bits will round number. toString(16) will convert number to hex string and ‘00000’ are needed for padding with leading zeros. All written in one line.

function rndColor() {
    return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6);
}

In Douglas Crockford’s book JavaScript: The Good Parts you can find a comment about slow number rounding with bitwise operators:

In Java, the bitwise operators work with integers. JavaScript doesn’t have integers. It only has double precision floating-point numbers. So, the bitwise operators convert their number operands into integers, do their business, and then convert them back. In most languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow. JavaScript is rarely used for doing bit manipulation.

However, I found several revisions of Rounding numbers down test in JavaScript. These tests show that bitwise left operator is almost two times faster in number rounding comparing to classic Math.floor() method. It seems that JavaScript engines are much faster since time when book was released – don’t you think?

3 thoughts on “JavaScript random color generator”

  1. Nice article.
    Here is a small improvement to your shortest rndColor function.

    function rndColor() {
        return '#'+('00000'+(Math.random()*(1<<25)).toString(16)).substr(-6);
    }
    

    Here’s my version for the shortest onliner.

    function rHex() {
        return '#000000'.replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});
    }
    
  2. @Larry Battle – Thank you very much for your JS code. Your contribution is more than welcome and is very useful for others.

Leave a Comment