Thursday, October 16, 2008

Making sense of Ternary

I don't know about you, but for the longest time I was confused as heck about the ternary operator. In the AS3 language reference, this is all you get about the ternary operator:
Evaluates expression1, and if the value of expression1 is true, the result is the value of expression2; otherwise the result is the value of expression3.
Not much, right? I would see lines of code like this and my brain would bust: " variable == null ? doSomething() : doSomethingElse();" For sanity's sake (both yours and mine), I'm going to flat out explain the ternary operator/operand/thing.

In TK terms, the ternary operator does this: "If the value before the question mark evaluates as being true, the first expression is called, otherwise the second one is called." FTW? Ok, I'll make it even easier with example code and comments:

//If someVariable is null, execute functionOne, otherwise execute functionTwo
someVariable == null ? functionOne() : functionTwo();

//The preceding line is basically the same as doing this:
if (someVariable == null) {
functionOne();
} else {
functionTwo();
}

So does that make sense? The ternary operator thing saves you 2-3 lines of code and can be used nearly anywhere. Here's some code in action:

this.getState() == States.OPEN ? this.dispatchEvent(new SomeEvent(SomeEvent.CLOSE)) : this.dispatchEvent(new SomeEvent(SomeEvent.OPEN));

Get it? Got it? Good! Now go out there and get some!

Labels: ,