0

I've found that undefined object property not equals to undefined.

if (obj.unexistingProperty === undefined) {
  // condition is false
}

if (typeof obj.unexistingProperty === 'undefined') {
  // condition is true
}

While debugger consoles (Firebug and Chrome dev tools) consider both conditions true.

What is the explanation for that?


As it turned out, the code took place inside of

function (undefined) {
  ...
}

that shadowed undefined in local scope.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • 2
    Could you have mistakenly redefined `undefined`? – icktoofay Sep 13 '15 at 22:49
  • @icktoofay is that even possible? chrome console wont let me – Jorg Sep 13 '15 at 22:50
  • [Both conditions are true](http://jsfiddle.net/j2x2q7wb/). – Spencer Wieczorek Sep 13 '15 at 22:51
  • @Jorg It's possible in older versions of JavaScript, but not in ES5. See [this answer](http://stackoverflow.com/a/4726848/2234742) in the suggested duplicate. – Maximillian Laumeister Sep 13 '15 at 22:52
  • Thank you for pointing that, @icktoofay ! Indeed, it was redefined with anonymous 'function (undefined, prop)', which I mistakenly considered a safe way to define waste callback arguments. You may file it as an answer if the question will be unmarked as duplicate. – Estus Flask Sep 13 '15 at 23:02
  • @MaximillianLaumeister The global `undefined` property can no longer be redefined, but can be shadowed with a local variable. – Oriol Sep 13 '15 at 23:04

1 Answers1

1

As it happens, undefined isn’t a keyword like null is—undefined, before ECMAScript 5, can be redefined to something else. If you’ve mistakenly set it to something else, like the number 5, then test something actually undefined against it for equality, you’ll pretty clearly end up with false. On the other hand, typeof ignores local bindings.

If you can avoid redefining undefined, that would be for the best. Other things you can do would be testing for equality against void 0 (void takes an expression, discards its value, and returns the real undefined) or, as prompted the question, use typeof to check for undefined instead.

icktoofay
  • 126,289
  • 21
  • 250
  • 231