Convert RGB to HEX: Snippet of the Day
Master a concise JavaScript snippet to convert RGB colors to HEX, with a painter’s palette analogy for vibrant web design.

Shashank
Convert RGB to HEX: Snippet of the Day
Think of RGB and HEX as two artists painting the same picture—one with red, green, and blue paints, the other with a single hex code. Converting between them is like translating colors for a web canvas. Today’s snippet transforms RGB to HEX in a few lines, making your web design palette pop. Let’s mix some colors!
The Snippet
Here’s a function to convert RGB to HEX:
function rgbToHex(r, g, b) {
return '#' + [r, g, b]
.map(x => Math.max(0, Math.min(255, x)) // Clamp to 0-255
.toString(16) // Convert to hex
.padStart(2, '0')) // Ensure two digits
.join('');
}
console.log(rgbToHex(255, 128, 0)); // Output: #ff8000
This snippet takes three numbers (red, green, blue) and returns a HEX color code (e.g., #ff8000
for orange).
How It Works
Let’s break it down:
- Input Validation: Each RGB value (0–255) is clamped using
Math.max(0, Math.min(255, x))
to ensure valid ranges. - Hex Conversion:
toString(16)
converts each number to hexadecimal (base-16). - Formatting:
padStart(2, '0')
ensures each hex value is two digits (e.g.,0
becomes00
). - Concatenation: The values are joined with a
#
prefix to form the HEX code.
Example usage:
console.log(rgbToHex(0, 255, 0)); // Output: #00ff00 (green)
console.log(rgbToHex(300, -10, 128)); // Output: #ff0080 (clamped values)
A Painter’s Palette
Imagine a painter (your app) mixing RGB paints for a canvas (the browser). The client wants the color in HEX for their style guide. This snippet translates your RGB mix into a HEX code, ensuring consistency across tools like CSS or design software.
Why It Matters
Color conversion is common in web development, from dynamic themes to data visualizations. Ever wonder why your app’s colors don’t match the designer’s spec? A reliable RGB-to-HEX converter bridges that gap.
Always validate RGB inputs, as invalid values can produce unexpected HEX codes.
The Future of Color
As CSS evolves with new color formats (like lab()
or lch()
), RGB-to-HEX conversion remains a staple for backward compatibility. Tools like color libraries (e.g., TinyColor) build on these snippets, but knowing the raw logic empowers you to customize.
What colors will you paint your app with? Try this snippet to sync your RGB and HEX palettes.