Convert RGB to HEX color in JavaScript

Implement a function in JavaScript that converts the RGB number to HEXA color codes.

Example

Input: 255, 51, 255 Output: "#ff33ff" 

RGB format is a combination of three colors, red, green, and blue in the range of 0 – 255. A hex color code is the hexadecimal representation of the RGB numbers.

Hexadecimal uses 16 unique symbols, representing values as “0 – 9” for value between 0 – 9 and “A – F” or “a – f” for value between “10 – 15”.

There are multiple ways in which we can convert a given number to a Hexa value, just pad the number with 0 if it is a single digit and append it with “#”.

Approach 1. Using toString() method

The toString() method accepts a radix value and converts the value to that.

const componentToHex = (c) => { const hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } const rgbToHex = (r, g, b) => { return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); } console.log(rgbToHex(255, 51, 255)); //"#ff33ff" 

Approach 2. Using left shift (<<) operator

const rgbToHex = (r, g, b) => { return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); } console.log(rgbToHex(255, 51, 255)); //"#ff33ff" 

Approach 3. Using Array.map

const rgbToHex = (r, g, b) => '#' + [r, g, b] .map(x => x.toString(16).padStart(2, '0')).join('') console.log(rgbToHex(255, 51, 255)); //"#ff33ff"