Nice conditional coding tip

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.

var newVar:String;
var flashVar:Object;
if(flashVar.foo != null)
{
	newVar = flashVar.foo;
}else{
	newVar = "defaultFoo";
}

Alternatively:

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:

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!


Posted

in

by

Tags:

Comments

Leave a Reply