RGB color to hexadecimal color JavaScript

JavascriptFront End TechnologyWeb DevelopmentObject Oriented Programming

We are required to write a JavaScript function that takes in a RGB color and returns its hexadecimal representation.

The function should take in an object containing three numbers representing the respective values of red green and blue color.

For example:

rgbToHex(0, 128, 192) should return '#0080C0'

The code for this will be −

const rgbColor = {
   red: 0,
   green: 51,
   blue: 155
}
function rgbToHex({
   red: r,
   green: g,
   blue: b
}) {
   const prefix = '#';
   const hex = prefix + ((1 << 24) + (r << 16) + (g << 8) + b)
   .toString(16)
   .slice(1);
   return hex;
};
console.log(rgbToHex(rgbColor));

Following is the output on console −

#00339b
raja
Published on 09-Oct-2020 14:34:37
Advertisements