Undefined, typeof undefined, hasOwnProperty

javascript

Solution

(UPDATE: You might want to check out this question: variable === undefined vs. typeof variable === "undefined").

In very old browsers (Netscape 2, IIRC, and possibly IE 4 or lower), you couldn’t compare a value with `undefined`, since that caused an error. In any (semi-) modern browser, however, there’s no reason to check `typeof value === 'undefined'` instead of `value === undefined` (except for paranoia that somebody might have redefined the variable `undefined`).

`hasOwnProperty` serves a different purpose. It checks if the object has a property with the given name, and not its prototype; i.e. regardless of the inherited properties. If you want to check whether an object contains a certain property, inherited or not, you should use `if ('c' in a) {`...

But basically, these will probably all work:

if (a.c === undefined) console.log('No c in a!');
if (typeof a.c === 'undefined') console.log('No c in a!');
if (!('c' in a)) console.log('No c in a!');
if (!a.hasOwnProperty('c')) console.log('No c in a!');

The main differences being that:

- `a.c === undefined` will produce an unexpected result if someone has done `undefined = 'defined'` or some such trick;

- `!('c' in a)` is not very readable (IMHO)

- `!a.hasOwnProperty('c')` will return `false` if the object `a` doesn’t contain a property `c`, but its prototype does.

Personally, I prefer the first since it’s more readable. If you’re paranoid and want to avoid the risk of a redefined `undefined`, wrap your code in a self-executing anonymous function as follows:

(function (undefined) {
  // in here, 'undefined' is guaranteed to be undefined. :-)

  var a = {

  };

})();

Problem

Take this snippet, ``` var a = { } if(typeof a.c === 'undefined'){ console.log('inside if'); } if(a.c === undefined){ console.log('inside if'); } ``` Both `if` results in `true`. Is there any difference in both statements specific to some browsers? Also, in my last project I have already used `typeof a.c == 'undefined'` numerous times to check values in `json` data. Now, I know that this is not good way, as some value may be `undefined` too, so my logic will fail. I should have used `hasOwnProperty` . But I am sure that no value will be `undefined` , can I use `typeof a.c == 'undefined'` in place of `hasOwnProperty` or should I change all my `typeof` with `hasOwnProperty`

Original source

Related problems