Colors can be represented in different formats depending on the context.
For example, on the web in CSS, you can represent colors using RGB, HSL, HEX, and HSB.
Unfortunately, there is no built-in way to convert between these in JavaScript, so we will need to write our own code.
In this post, we will learn how to convert from RGB to Hex, the most popular format for colors.
How to convert from RGB to Hex
The biggest difference between these two values is that the RGB value is a 3-tuple of numbers between 0 and 255, and the Hex value is a 6-digit string.
Let's first start with the RGB value.
JAVASCRIPT
const red = 255;
const green = 0;
const blue = 0;
Now let's define a function that takes a single color and converts it to its hex representation.
For this, we will make use of the toString(16) method, which converts a number to a hexadecimal string.
If the value is only one digit, it will be padded with a 0.