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
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.
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.
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.