views:

534

answers:

7

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.

A: 

? : isn't this the ternary operator?

var x= expression ? true:false

jldupont
+2  A: 

It's the ternary operator: http://en.wikipedia.org/wiki/Ternary_operation.

jaxvy
Fixed. (15 char.)
Lucas Jones
+2  A: 

Properly parenthesized for clarity, it is

hsb.s = (max != 0) ? (255 * delta / max) : 0;

meaning return either

  • 255*delta/max if max != 0
  • 0 if max == 0
Jason S
A: 

This 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.

Nikolas Stephan
+1  A: 

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/

Josh W.
+6  A: 

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;
Greg
"?" isn't the ternary operator; "? :" is the ternary operator. Talking about "?" as the ternary operator is like talking about Abbott without Costello, Laurel without Hardy, Cheech without Chong....
Jason S
Ok, ok... now I'm using an ambiguous pronoun, happy? :)
Greg
sure. one good ternary operator deserves another....
Jason S
@Jason: What an awful pun. A wonderful, awful pun!
ThisSuitIsBlackNot
+3  A: 

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;
}
Chad