Random Hex Colour Generator in JavaScript

June 26, 2020

Hexadecimal

The Hexadecimal can contain numbers from 0-9 and can contain alpha letters from a-f. So let's define a array which store these values

var hex = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'];

Generating random numbers

To generate Random number , you can use Math.random() which will return floating-point, pseudo-random number in the range 0 to less than 1 (0 included, but not 1).

You can check by

// try in browser console
Math.random(); //0.18734993728653526
Math.random(); //0.5966283437784992
Math.random(); //0.17585611438313142

You can multiply the length of the hex array(16) with the random number, we get any index between 0 to 16.

// try in browser console
Math.random() * 16; //15.706413080165255
Math.random() * 16; //11.603658476251027
Math.random() * 16; //12.843853790915077

Here all the values are in floating point. To convert the floating point to whole number , you can use Math.floor() which will return the largest integer less than or equal to the specified number.

Math.floor(15.706413080165255); // 15
Math.floor(11.603658476251027); //11
Math.floor(12.843853790915077); //12

Now we can apply floor operation to the randomly generated number, to get the index

let randNumber = Math.random() * 16;
let index = Math.floor(randNumber);  

A hex colour code starts with # and can have either 3 or 6 characters , here I will be generating 6 characters, for that we need to create a loop which will run 6 times on each time random character is picked from hex array and appended to a string

function getRandHex() {
    let hexCode = "#";
    const HEX = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'];
    const HEX_LENGTH = 6;
    for(let i = 0; i < HEX_LENGTH; i++){
        let randNumber = Math.random() * 16;
        let index = Math.floor(randNumber);  
        hexCode += HEX[index];
    }
    return hexCode;
}