Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

self learner
self learner
1,556 Points

Can you pls explain what is happening in this rgb to hex conversion ?

function componentToHex(c) {
    var hex = c.toString(16);
    return hex.length == 1 ? "0" + hex : hex;
}

1 Answer

Here's an explanation of the toString() method used (quick answer: it converts the value passed into the function into a hexadecimal value).

Here's an explanation of the ternary operator used (quick answer: if the calculated hex value is only 1 character long, add a zero to the beginning of it -- since color hex codes need to be 2 characters long, then return it). It may be easier to read that line as:

return (hex.length == 1) ? "0" + hex : hex;

Written out in longer form, the following is an exact replica of that one compact line:

if (hex.length == 1) {
  hex = "0" + hex;
}
return hex;

People use ternary operators to make their code more concise. If you're new to them, I understand they can be more confusing, but you'll get used to them.