' 09 May, 28 - 12:00 pm
Cool Flash Tip of the Week 1
I’m going to start a series that will occur every week. A cool flash tip or something I think not many people know about. Be on the lookout every week for a new tip. This week’s CFT is ……drumroll…….” The Tertiary Operator “.
I spend alot of time traversing flash posts looking at other peoples code and I often see a large if else block to change a simple variable. Using the Tertiary Operator we can simplify this into one line of code. Shorter code is always better in my opinion. Plus can save you a couple bytes in your code.
Here is an example of what I see.
var myBool:Boolean = false; var myVar:Number = 12; if(myBool == true) { myVar = 15; } else if(myBool == false && myVar == 10) { myVar = 40; } else { myVar = 0; }
Now this is all well and dandy, but it is a waste of space and can be simplified by a lot. One, when testing a Boolean there is no need to test to true or false. Instead if you want to test if something is true, you can just place the variable in the if parenthesis. This will automatically test to true. To test if a variable is false, use !. Here is an example.
var myBool:Boolean = false; var myVar:Number = 12; if(myBool ) { myVar = 15; } else if(!myBool && myVar == 10) { myVar = 40; } else { myVar = 0; }
This already shortens up our code a bit. But we can take this a step further using the Tertiary Operator. The syntax for this is pretty simple once you know what it means.
//Tertiary Syntax (Test) ? True : False;
Basically, If the test is true, the code after the ? executes. If the test is false the code after the : executes.
- ? = if
- : = else
You can also string together Tertiary statements to make and if else if else etc. Here’s how we write the same code from above over using the Tertiary Operator.
var myBool:Boolean = false; var myVar:Number = 12; myVar = (myBool ) ? 15 : (!myBool && myVar == 10) ? 40 : 0;
WOW, look how much space we saved, and it i still readable. I implore everyone to start using this and save space =D. Be aware that it is advised no to string Tertiary statements past “If..Else”. If you liked this idea of CFT ( Cool Flash Tip ), then leave a comment, subscribe to the feed or / and follow me on twitter. It would be great to get some feedback on if this is helpful or not and maybe some tips you would like to see featured here.
Happy Flashing
No related posts.
Feed Me
Feed Me via Email
Follow Me on Twitter
I'm LinkedIn





Comments