ECMAScript question detail
hasOwn
The new Object.hasOwn() method is a replacement or improved version of Object.prototype.hasOwnProperty. It is a static method that returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false.
It's not only more concise and readable but also overcomes the below limitations of hasOwnProperty.
- When
hasOwnPropertyoverwritten:
There are cases where you need to define customized hasOwnProperty on the object. When you try to apply hasOwnProperty to determine the own property or not, it throws an error as shown in below example.
const user = {
age: 35,
hasOwnProperty: ()=> {
return false;
}
};
user.hasOwnProperty('age') // throws a TypeError
This issue can be solved by hasOwn method .
const user = {
age: 35,
hasOwnProperty: ()=> {
return false;
}
};
user.hasOwn('age') // true
- Create an object with create(null) function:
If you create new object with help of create(null) function, then newly created object doesn’t inherit from Object.prototype. So it doesn't have hasOwnProperty method.
Let's take an example to verify hasOwnProperty on an object created with create(null) function.
const user = Object.create(null);
user.age = 35;
user.hasOwnProperty('age'); // throws a TypeError
In this case, hasOwn() method can be used to determine the own property.
const user = Object.create(null);
user.age = 35;
user.hasOwn('age'); // true