Question

What is the better solution?

if(typeof bla === "undefined" || bla === null)...

Or

if(bla)...

If I do the second solution, do I really need to check whether its undefined?

Thanks.

Was it helpful?

Solution

That depends on what you expect the variable to contain.

If it should for example contain an object, the second option works fine because any object reference is truthy.

If it should for example contain a boolean value, the second option won't work at all, because false would give the same result as a non-existing value.

OTHER TIPS

do I really need to check whether its undefined?

No, both undefined and null resolve to false. Second option is definitely better.

To "check if undefined", the best solution is usually a third one :

Demo

function isDef(obj) {
    var undefined;
    return obj === undefined;
}

This checks if the object is undefined without losing time with typeof and this test doesn't validate as true with "", null, NaN or 0 as would your second test.

The only pitfall is that someone can override the global undefined object. Not possible in ES5 strict mode, but your code should shield from this. Shadowing undefined with a local var undefined; definition does that for you.

Also, by using an isDef function you allow for better, portable minification and simpler logic.

if (isDef(x)) {
    // do something
} else {
    // do something else
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top