javascript - Undefined, typeof undefined, hasOwnProperty -


take snippet,

var = {  }  if(typeof a.c === 'undefined'){  console.log('inside if'); } if(a.c === undefined){  console.log('inside if'); } 

both if results in true. is there difference in both statements specific browsers?

also, in last project have used typeof a.c == 'undefined' numerous times check values in json data.

now, know not way, value may undefined too, logic fail.

i should have used hasownproperty .

but sure no value undefined , can use typeof a.c == 'undefined' in place of hasownproperty or should change typeof hasownproperty

(update: might want check out question: variable === undefined vs. typeof variable === "undefined").

in very old browsers (netscape 2, iirc, , possibly ie 4 or lower), couldn’t compare value undefined, since caused error. in (semi-) modern browser, however, there’s no reason check typeof value === 'undefined' instead of value === undefined (except paranoia might have redefined variable undefined).

hasownproperty serves different purpose. checks if object has property given name, and not prototype; i.e. regardless of inherited properties. if want check whether object contains property, inherited or not, should use if ('c' in a) {...

but basically, these 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 produce unexpected result if has done undefined = 'defined' or such trick;
  • !('c' in a) not readable (imho)
  • !a.hasownproperty('c') return false if object a doesn’t contain property c, prototype does.

personally, prefer first since it’s more readable. if you’re paranoid , want avoid risk of redefined undefined, wrap code in self-executing anonymous function follows:

(function (undefined) {   // in here, 'undefined' guaranteed undefined. :-)    var = {    };  })(); 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -