I've just taken over a project from another developer and the code has a lot of if statements like this:
if( value != null || value != "" || value != undefined )
{
doSomeThing();
}
Which while ok, does get a bit messy when used everywhere. Is there a better, neater way to write this? I was thinking of this
if( value.length > 0 || value != undefined )
{
doSomeThing();
}
What do you all think?
Thanks
Stephen
It's nearly that, but with if( value.length > 0 || value != undefined )
when value is null
value.length
will thhrow a runtime error TypeError: Error #1009 as you are trying to access a property on a null
value.
so you have to check before that the value is non null as for example :
if (value!=null&&value.length>0) {doSomeThing();}
or another form shorter :
if ((value||"").length>0) {doSomeThing();}
One note:
Unless the type of value is *
, it can't take the value undefined, it will be null
.
var str:String=undefined;
trace(str==null); // will output true
I love to write statements more positive. The statements of the programmer checks if something is not null, but he means; if it exist:
In case of arrays or strings I use this:
if ( value && value.length > 0 ) doSomething();
But in cases of objects or DisplayObjects I use this to check if it exist.
if ( mc ) doSomething();
In most cases this is enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With