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());