Skip to content Skip to sidebar Skip to footer

Javascript Test ( Object && Object !== "null" && Object !== "undefined" )

I seem to be using this test a lot if( object && object !== 'null' && object !== 'undefined' ){ doSomething(); } on objects I get back from a service call or f

Solution 1:

I don't think you can make that any simpler, but you could certainly refactor that logic into a function:

functionisRealValue(obj)
{
 return obj && obj !== 'null' && obj !== 'undefined';
}

Then, at least your code becomes:

if (isRealValue(yourObject))
{
 doSomething();
}

Solution 2:

If you have jQuery, you could use $.isEmptyObject().

$.isEmptyObject(null)
$.isEmptyObject(undefined)
var obj = {}
$.isEmptyObject(obj)

All these calls will return true. Hope it helps

Solution 3:

if(!!object){
  doSomething();
}

Solution 4:

If object is truthy, we already know that it is not null or undefined (assuming that the string values are a mistake). I assume that a not null and not undefined test is wanted.

If so, a simple comparison to null or undefined is to compare != null.

if( object != null ){
    doSomething();
}

The doSomething function will run only if object is neither null nor undefined.

Solution 5:

maybe like this

if (typeofobject !== "undefined" || object !== null)
    // do something

Post a Comment for "Javascript Test ( Object && Object !== "null" && Object !== "undefined" )"