18 Dec 2007

If Else Shorthand Using The Ternary Operator

The ternary operator ?: is a rarely used operator which can be used to write shorthand code that reads well.

For example,

if (condition) {
  task1;
}
else {
  task2;
}

can be replaced with the much cleaner

(condition) ? task1 : task2;

Here are a few examples.