How to determine if Native JavaScript Object has a Property/Method?

scunliffe picture scunliffe · Feb 27, 2009 · Viewed 47.2k times · Source

I thought this would be as easy as:

if(typeof(Array.push) == 'undefined'){
  //not defined, prototype a version of the push method
  // Firefox never gets here, but IE/Safari/Chrome/etc. do, even though
  // the Array object has a push method!
}

And it does work fine in Firefox, but not in IE, Chrome, Safari, Opera, they return all properties/methods of the native Array object as 'undefined' using this test.

The .hasOwnProperty( prop ) method only works on instances... so it doesn't work, but by trial and error I noticed that this works.

//this works in Firefox/IE(6,7,8)/Chrome/Safari/Opera
if(typeof(Array().push) == 'undefined'){
  //not defined, prototype a version of the push method
}

Is there anything wrong with using this syntax to determine if a property/method exists on a Native Object / ~"JavaScript Class"~, or is there a better way to do this?

Answer

Barney picture Barney · Mar 21, 2010

The proper way to check if a property exists:

if ('property' in objectVar)