We know how to do it with functions how to set a default value when nothing comes through but what about variables such as in scenarios of flash vars where we just don't know until run time if we are going to get the variables or not.
Like anything cool in the world of programing there are a few options. The first is a traditional if statement asking our variable if its empty or not but then that wouldn't be such a cool trick if that was the full solution. come join in this is really cool...
The problem:
Your expecting some data but you don't know if its going to come through or not such as through a flash var.
lets say your confronted with a variable that you just don't know if it has something in it but if it doesn't have any value in it(and lets assume in this scenario that we mean that o,undefined,null false are all not acceptable results) you really want it to be equal to 1. The most natural thing you might be thinking is to use a traditional if statement:
i(a==null || a==0 || a==false){
a=1;
}
but that was a heck of a lot of code and yea your right because we said we are treating false,0,null and undefined as just not valid answers we can make it a bit easier as well:
if(!a){
a=1;
}
Well that saved us some typing that was nice. but still if you had a really big amount of variables to check your code would just grow so much and be hard to manage so yep you might be thinking its a great time to use Ternary operations
a = a?a:1; //or if(!a) a=1;
both are nice and short but our ternary operation is a bit over kill right we are assigning the same value into our a when a has a valid value.
ok time for my fav:
var a:int; a||=1; trace(a);
and if this isn't cool then i don't know what's cool. lets break this apart to understand what's going on:
when we are using the or operator (||) the rules of flash are that it checks the first condition if it comes back true it will never look into the next operator and thous :
trace( 10 || 5);
would return 10 as it is a valid value its not 0,null,undefined,false so it returns 10). and as we are working with an OR assignment operator what we are actually doing is placing into our a or the value of a if it has a value or the value of b :
a||=b;
so if our 'a' had a value it would remain that value if not it would turn into the value of b.
Warning: Most developers don't even know about this. With that said you might generate some head pain for some so think twice when you use it when working in a team.
_
Ben Fhala
Flash/AS3 School || Follow @02geek || Youtube Channel || EventController || More Recipes
In the spotlight:
ActionScript 3.0 Developer foundations running though all the core consepts of programing
P.S. If you want to call my attention to a request
add
@02geek to the title or twitter
my nickname and a link to your post.
+