0

I have been reviewing other peoples javascript codes and noticed variable lines like this:

opacity = isIn ? 0 : 1;,

opacity = isIn ? opacity + gap : opacity - gap;,

var s = this == binary ? h(binary, f, change, text) : h(text, r, change2, binary);,

And other lines of code like that. How do they work? What type of variable are they?

Thank you so much!

  • possible duplicate of [What does the question mark and the colon (?: ternary operator) mean in objective-c?](http://stackoverflow.com/questions/2595392/what-does-the-question-mark-and-the-colon-ternary-operator-mean-in-objectiv) – Quentin Oct 16 '13 at 11:50

2 Answers2

3

This is a special form of if called a conditional (or ternary) operator:

var value = condition ? value_when_true : value_when_false;

If the condition evaluates to true, value will be assigned value_when_true, if not, value_when_false.

It is functionally the same as:

var value;
if (condition) {
  value = value_when_true;
} else {
  value = value_when_false;
}

See this MDN article for detailed description.

kamituel
  • 34,606
  • 6
  • 81
  • 98
  • 1
    @CodeApprentice remember that just like in an `if`, `value_when_true` and `value_when_false` can be any expression you want evaluated, as long as the interpreter doesn't encounter a line delimiter `;` (using `,` instead tends to be okay). You may want to use parenthesis if doing multiple `?:`s and if it starts to look complicated, it's usually easier for everyone if you switch to a normal `if`. – Paul S. Oct 16 '13 at 12:00
1

Its called ternary operators

http://msdn.microsoft.com/en-us/library/ie/be21c7hw%28v=vs.94%29.aspx

var s = (some_condition) ? if_true_value : if_false_value;

same as

if(some_condition){
   s = if_true_value;
}else{
   s = if_false_value;
}
coolguy
  • 7,866
  • 9
  • 45
  • 71