Skip to content

JavaScript hasOwnProperty | Method

  • by

Use JavaScript Object hasOwnProperty() method to check if the object has the given property as its own property. This returns true if the specified property is a direct property of the object — even if the value is null or undefined.

And it returns false if the property is inherited or has not been declared at all.

object.hasOwnProperty(property)
  • object: The object you want to check for the presence of a property.
  • property: A string representing the name of the property you want to check.

Note: Object.hasOwn() is recommended over hasOwnProperty(), in browsers where it is supported.

JavaScript hasOwnProperty method

Simple example code.

  <!DOCTYPE html>
  <html>
  <body>

    <script>
     var x = {
      'key': 1
    };

    if ( x.hasOwnProperty('key') ) {
      console.log('has key property');
    }

  </script>

  </body>
  </html> 

Output:

JavaScript hasOwnProperty Method

More Examples

var x = {
    y: 10
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false
const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));
// expected output: true

It’s important to note that hasOwnProperty() only checks for direct properties and doesn’t traverse the prototype chain. If you want to check for a property that may be inherited from a prototype, you can use the in operator or the Object.prototype.hasOwnProperty() method on the object:

const person = {
  name: 'John',
  age: 30,
};

console.log('name' in person);  // true
console.log('toString' in person);  // true (inherited from Object.prototype)

Both the hasOwnProperty() method and the in operator can be useful in different scenarios, depending on whether you want to check for direct properties or properties anywhere in the prototype chain.

Do comment if you have any doubts or suggestions on this JS method code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *