Nick G. Nick G. - 4 months ago 17
Javascript Question

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 from reading cookies (since different browsers return the different values
null
,
undefined
,
"null"
, or
"undefined"
).

Is there an easier/more efficient way of doing this check?

Answer

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

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

Then, at least your code becomes:

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