Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptJavaScript hasOwnProperty() Method

JavaScript hasOwnProperty() Method

The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being it’s own.

Syntax:

object.hasOwnProperty( prop )

Parameters: This method accepts a single parameter.

  • prop: It holds the name in the form of a String or a Symbol of the property to test.

Return Value: It returns a boolean value indicating whether the object has the given property as its own property.

The below examples illustrate the JavaScript hasOwnProperty() Method:

Example 1: This example checks the properties of an object.

Javascript




function checkProperty() {
    let exampleObj = {};
    exampleObj.height = 100;
    exampleObj.width = 100;
 
    // Checking for existing property
    result1 = exampleObj.hasOwnProperty("height");
 
    // Checking for non-existing property
    result2 = exampleObj.hasOwnProperty("breadth");
 
    console.log(result1);
 
    console.log(result2);
}
checkProperty()


Output

true
false

Example 2: This example checks the properties of an object of a class.

Javascript




function checkProperty() {
 
    function Car(a, b) {
        this.model = a;
        this.name = b;
    }
 
    let car1 = new Car("Mazda", "Laputa");
 
    // Checking for existing property
    result1 = car1.hasOwnProperty("model");
 
    // Checking for non-existing property
    result2 = car1.hasOwnProperty("wheels");
 
    console.log(result1);
 
    console.log(result2);
}
checkProperty()


Output

true
false

We have a complete list of Object methods, and properties to check those please go through this JavaScript Object Complete Reference article.

Supported Browsers: The browsers supported by JavaScript hasOwnProperty() method are listed below.

  • Google Chrome 1 and above
  • Firefox 1 and above
  • Internet Explorer 5.5 and above
  • Edge 12 and above
  • Safari 3 and above
  • Opera 5 and above

RELATED ARTICLES

Most Popular

Recent Comments