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"