Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a better way to check a value is not blank or null than this

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

like image 907
StephenAdams Avatar asked Dec 05 '22 00:12

StephenAdams


2 Answers

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
like image 115
Patrick Avatar answered Dec 31 '22 07:12

Patrick


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.

like image 37
Mark Knol Avatar answered Dec 31 '22 08:12

Mark Knol