Shorthand 'if else' Statement (ternary)
Sat Dec 26 04:15:23 2009
There's a lot to be learnt from simple reviewing the basics of programming on occasion, as my recent experiences have shown. Today, I would like to share a little shorthand 'conditional statement' with you that I've picked up along the way, which may help from time to time in your own coding.
As you may already know, the most commonly seen conditional statement syntax in ActionScript 3.0 is as follows:
Example 1
var sayHello:Boolean = false; if(sayHello == true){ trace("hello"); }else if(sayHello == false){ trace("goodbye"); } //traces("goodbye");
This can be shorted to a single line in most, if not all programming languages to something like the following:
(checkstatement)? doSomething() : doSomethingElse();
So if you wanted to do the same thing as the if statement in Example 1 above, you might do this:
var sayHello:Boolean = false; (sayHello)? trace("hello") : trace("goodbye"); //traces goodbye sayHello = true; (sayHello)? trace("hello") : trace("goodbye"); //traces hello
In actual fact, I have to confess that this is something that I have learnt from my endeavours into the world of PHP, but its use is far wider and I'm sure that it will help make your coding a little bit tidier and easier to read. If anyone discovers any limitations to either way, I would love to hear about them.
Tweet← back