Javascript array key exists / Javascript hasOwnProperty

Share Button


In javascript if you want to check if there a key that exists in a javascript array or a javascript object, you need to use hasOwnProperty() method of javascript.

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike thein operator, this method does not check down the object’s prototype chain.


Using hasOwnProperty to test for a property’s existence

The following example determines whether the o object contains a property named prop:

o = new Object();
o.prop = 'exists';

function changeO() {
  o.newprop = o.prop;
  delete o.prop;

o.hasOwnProperty('prop');   // returns true
o.hasOwnProperty('prop');   // returns false
Share Button