HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Generating a random hex color

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomhexgeneratingcolor

Problem

Is there any better way of doing this?

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

Solution

Hex colors can be in 3 digits or 6 digits. In the case where you want 3 digits, you can't do it because 6 is hardcoded. You may want to move it into a variable with a default value of 6.

Strings characters in JS are accessible via indices the same way as an array. So splitting the characters into an array is unnecessary, not to mention the additional memory consumed by creating an array.

Adding | 0 after a number truncates the decimal places from the number. Internally, it converts the internal representation of the number from a float into an integer, dropping the decimal information. So basically, it does the same thing as Math.floor, albeit in a more vague but shorter way.

You could also use reverse looping, and using the length as the condition. When length is zero, it's essentially falsy, thus stopping the loop.



function getRandomColor() {
var length = 6;
var chars = '0123456789ABCDEF';
var hex = '#';
while(length--) hex += chars[(Math.random() * 16) | 0];
return hex;
}

document.write(getRandomColor());

Context

StackExchange Code Review Q#108130, answer score: 8

Revisions (0)

No revisions yet.