hasOwnProperty() in Javascript

    May 13, 2020       by Pankaj Kumar
javascript-hasownproperty-method.jpg

In this article, We will see the working of hasOwnProperty() method in Javascript. This method is mainly used to check whether has specified properties. If the property exists in the object then true is returned otherwise false is returned.

 

hasOwnProperty() Syntax

obj.hasOwnProperty(property)

 

  • Property: It is the string name or object which is needed to check if it below to the object Obj.
  • Return value: Returns a boolean on the base of existence of the property 

Note: This method returns true even if the property value is null or undefined

 
o = new Object();
o.propOne = null;
o.hasOwnProperty('propOne'); // returns true
o.propTwo = undefined;
o.hasOwnProperty('propTwo'); // returns true
 

 

hasOwnProperty() Examples

Check the property existence

 

 
o = new Object();
o.hasOwnProperty('prop'); // returns false
o.prop = 'exists';
o.hasOwnProperty('prop'); // returns true

 

 

Iterating over the properties of an object

In the example below, we will see how to iterate over the properties of an object without executing on inherited properties.

 

 
var buz = {
  fog: 'stack'
};
 
for (var name in buz) {
  if (buz.hasOwnProperty(name)) {
    console.log('this is fog (' +
    name + ') for sure. Value: ' + buz[name]);
  }
  else {
    console.log(name); // toString or something else
  }
}
 

 

Thank you!


WHAT'S NEW

Find other similar Articles here: