Nice conditional coding tip

Posted By Thaylin on May 13, 2010

Tyler from FCNY turned me on to a nice tip on conditional coding.

Let’s take for example we have a variable that we need to associate with another variable. For instance, we pull in some flashvars and need to check if these exist and if not give them a default value. Let’s look at a couple of the standard ways we can do this.

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
var newVar:String;
var flashVar:Object;
if(flashVar.foo != null)
{
	newVar = flashVar.foo;
}else{
	newVar = "defaultFoo";
}

Alternatively:

?View Code ACTIONSCRIPT
1
newVar = (flashVar.foo != null) ? flashVar.foo : "defaultFoo" ;

both of these are perfectly valid and legitimate. The first being much more readable than the second. But what about another way?

How about:

?View Code ACTIONSCRIPT
1
newVar = ( flashVar.foo || "defaultFoo" );

Nice, short and more readable, this line says if the flashVar.foo has no value then assign it the other value. However, this wouldn’t be the best option if you’re looking for numbers and a valid number would be 0 as that would return a false within the OR statement check. So use with caution.

Thanks Tyler!


Comments

Leave a Reply

Please note: Comment moderation is currently enabled so there will be a delay between when you post your comment and when it shows up. Patience is a virtue; there is no need to re-submit your comment.