DEV Community 👩‍💻👨‍💻

Discussion on: Different possible methods for generating a colour randomly in JS

Collapse
 
lukeshiru profile image
Luke Shiru

Thanks for the credit!

About this post, something that might be useful for you: To pad zeroes to a string, you can use the native String.prototype.padStart instead of concatenating "0" and then slicing. Here are the examples:

For method 4:

function getRandomColor() {
    function c() {
        return Math.floor(Math.random() * 256)
            .toString(16)
            .padStart(2, "0");
    }
    return "#" + c() + c() + c();
}
Enter fullscreen mode Exit fullscreen mode

And if we take it one step further:

const getRandomHex = () =>
    Math.floor(Math.random() * 0xff)
        .toString(16)
        .padStart(2, "0");

const getRandomColor = () =>
    `#${getRandomHex()}${getRandomHex()}${getRandomHex()}`;
Enter fullscreen mode Exit fullscreen mode

For method 5:

function getRandomColor() {
    return "#" + Math.random().toString(16).slice(2, 8).padStart(6, "0");
}
Enter fullscreen mode Exit fullscreen mode

And also taking it one step further:

const getRandomColor = () =>
    `#${Math.random().toString(16).slice(2, 8).padStart(6, "0")}`;
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
 
prakhart111 profile image
Prakhar Tandon Author • Edited on

Okay great, well that's the benefit of an active community, you learn everyday!
And your comments just enhance my article thanks for this
and Cheers!