I came across the following line in a JS function (it was an RGB to HSB color converter, if you must know)
hsb.s = max != 0 ? 255 * delta / max : 0;
I'm wondering if someone can explain what the "?" and the ":" mean in this context.
I came across the following line in a JS function (it was an RGB to HSB color converter, if you must know)
hsb.s = max != 0 ? 255 * delta / max : 0;
I'm wondering if someone can explain what the "?" and the ":" mean in this context.
It's the ternary operator: http://en.wikipedia.org/wiki/Ternary_operation.
Properly parenthesized for clarity, it is
hsb.s = (max != 0) ? (255 * delta / max) : 0;
meaning return either
255*delta/max
if max != 00
if max == 0This is probably a bit clearer when written with brackets as follows:
hsb.s = (max != 0) ? (255 * delta / max) : 0;
What it does is evaluate the part in the first brackets. If the result is true then the part after the ? and before the : is returned. If it is false, then what follows the : is returned.
That's the ternary operator. It's a shortcut for if/then/else
http://www.gsdesign.ro/blog/how-to-use-ternary-operator-in-javascript/
It is called the Ternary Operator.
It has the form of: condition
? value-if-true
: value-if-false
Think of the ?
as "then" and :
as "else".
Your code is equivalent to
if (max != 0)
hsb.s = 255 * delta / max;
else
hsb.s = 0;
hsb.s = max != 0 ? 255 * delta / max : 0;
? is a ternary operator, it works like an if in conjunction with the :
!= means not equals
So, the long form of this line would be
if (max != 0) { //if max is not zero
hsb.s = 255 * delta / max;
} else {
hsb.s = 0;
}