0

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.

Christian
  • 6,961
  • 10
  • 54
  • 82
  • 3
    The answer is "it depends on what exactly you are trying to do". – karim79 Jun 25 '13 at 12:22
  • "Really check if undefined"... do you mean that, or do you mean "undefined or null", since you are checking for null too in those examples. – James Allardice Jun 25 '13 at 12:24
  • A property, when it has no definition, is undefined. Put that way, it's pretty obvious. null is an object. It's type is null. undefined is not an object, it's type is undefined. That part is less obvious. http://stackoverflow.com/questions/6429225/javascript-null-or-undefined – HIRA THAKUR Jun 25 '13 at 12:27

3 Answers3

3

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • So to be sure, check for undefined and null is the better solution? – Christian Jun 25 '13 at 12:27
  • @Christian: That depends on what you need to be sure of. There is no ideal method that works for all situations. A `null` value can for example be a perfectly valid value in some situations. – Guffa Jun 25 '13 at 16:06
0

do I really need to check whether its undefined?

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

mohkhan
  • 11,925
  • 2
  • 24
  • 27
0

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
};
flavian
  • 28,161
  • 11
  • 65
  • 105
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758