Estus Flask
Estus Flask

Reputation: 223104

Undefined object property not equals to `undefined`

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.

Upvotes: 0

Views: 100

Answers (1)

icktoofay
icktoofay

Reputation: 129139

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.

Upvotes: 1

Related Questions