Introduction
In this lab, we will be exploring the process of converting RGB values to hexadecimal color codes in JavaScript. We will be using bitwise left-shift operator and Number.prototype.toString() to convert the given RGB parameters to a 6-digit hexadecimal value using String.prototype.padStart(). This lab will help you understand the conversion process and give you hands-on experience with the implementation of the algorithm in JavaScript.
RGB to Hex Converter
To convert RGB values to a hexadecimal color code:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the following function:
const RGBToHex = (r, g, b) =>
((r << 16) + (g << 8) + b).toString(16).padStart(6, "0");
- Call the function with the RGB values as arguments to get a 6-digit hexadecimal value.
For example:
RGBToHex(255, 165, 1); // 'ffa501'
Summary
Congratulations! You have completed the RGB to Hex lab. You can practice more labs in LabEx to improve your skills.