January 10, 2007

The Ternary Operator

Using many if or switch statements can make your code very long and complex in no time. A trick to avoid some of the bloating involves using something called the ternary operator.

The ternary operator syntax is:

var variable = condition ? trueValue:falseValue;

This is very handy for boolean conditions or very short values.

For example, you can replace this long if condition with one line of code:

// Normal syntax
 
var direction;
 
if (x < 200) {
 
    direction = 1;
 
}  else  {
 
    direction = -1;
}
 
// Ternary operator
 
var direction = x < 200 ? 1 : -1;