Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Object hasOwn() Method

JavaScript Object hasOwn() Method

JavaScript hasOwn() method is used to check if the object has the specified property or not. It returns true if the property exists else false. This method was introduced as a replacement for the Object.hasOwnProperty() method. It is different from in operator as it does not check for inherited properties.

Syntax:

Object.hasOwn(obj, prop)

Parameters: This method takes two parameters

  • obj: This is the JavaScript object on which the check is to be applied
  • prop: It is the property on which the check is to be applied

Return Value: A boolean value true if exists else false.

Example 1: This example uses the hasOwn() method to check if a property exists or not

Javascript




let details = {
    name: "Raj",
    course: "DSA",
    website: "geeksforgeeks.org",
}
  
console.log(Object.hasOwn(details, 'name'));
console.log(Object.hasOwn(details, 'course'));
console.log(Object.hasOwn(details, 'phone number'));


Output:

true
true
false

Example 2: This example will compare the in operator and Object.hasOwn() method.

Javascript




let details = {
    name: "Raj",
    course: "DSA",
    website: "geeksforgeeks.org",
}
  
console.log(Object.hasOwn(details, 'name'));
console.log('name' in details);
  
console.log(Object.hasOwn(details, 'toString'));
console.log('hasOwnProperty' in details);


Output: The in operator returns true for even inherited properties like toString is an inherited method for all JavaScript objeccts.

true
true
false
true

Example 3: This method compares the hasOwnProperty() method and hasOwn() method.

Javascript




let details = Object.create(null);
details.course = "DSA";
  
console.log(Object.hasOwn(details, "course"));
console.log(Object.hasOwnProperty(details, "course"))


Output: The hasOwnProperty() method does not work on null objects but hasOwn() method works. So it is better than hasOwnProperty() method

 

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments