DEV Community 👩‍💻👨‍💻

Cover image for Convert RGB to Hex color codes in JavaScript
coder4life
coder4life

Posted on

Convert RGB to Hex color codes in JavaScript

Sometimes you have the RGB color code but you just really want the Hex code, right? Well converting RGB to Hex is so easy in JavaScript!

const rgb2hex = (r, g, b) => {
    return '#' +
        (
            (1 << 24) +
            (r << 16) +
            (g << 8) +
            b
        )
        .toString(16).slice(1);
};

console.log(rgb2hex(0, 0, 0));
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
lukeshiru profile image
Luke Shiru

You could simplify your code a little, and add some defaults to avoid NaNs:

const rgb2hex = (red = 0, green = 0, blue = 0) =>
    `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`;
Enter fullscreen mode Exit fullscreen mode

I would personally do it this way instead:

const decimalToHex = (decimal = 0) => decimal.toString(16);

const rgb2hex = ({ red = 0, green = 0, blue = 0 }) =>
    `#${[red, green, blue].map(decimalToHex).join("")}`;
Enter fullscreen mode Exit fullscreen mode

Cheers!

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!