Object introduced hasOwn method in ES2022 language.
hasOwn
is a static method in the Object class, to check given property is its own property or not. It returns true if the given property is its own property, else returns false.
what does own property mean in an object?
If an object contains inherited properties via prototype inheritance or does not exist, it returns false.
hasOwn
is a replacement for hasOwnProperty
method.
hasOwn(Object, property)
Object is an object to test property
Here is an example
const employee = {
id: '1',
};
console.log(Object.hasOwn(employee, 'id')); // true
console.log(Object.hasOwn(employee, 'name')); // false
console.log(Object.hasOwn(employee, 'salary')); //false
Javascript Check if an object has a property or not
It is easy to check whether an object has a property or not using hasOwn
or hasOwnProperty
methods of an Object class
hasOwn is a static method hasOwnProperty is not static, but the instance method
hasOwn example:
const student = { name: 'abc' };
console.log(Object.hasOwn(student, 'name'));// true
console.log(Object.hasOwn(student, 'id'));// false
hasOwnProperty example
const student = { name: 'abc' };
console.log(student.hasOwnProperty('name'));// true
console.log(student.hasOwnProperty('id'));// false
difference between Object.hasOwn vs Object.prototype.hasOwnProperty
Both are used to check object’s Own property exists or not, and return a boolean true or false. However, there are a couple of differences when to use one.
hasOwn is a Static method that can be used as given below.
Object.hasOwn(obj,property)
hasOwnProperty is an instance method that can be used as given below.
Object.hasOwnProperty(property)
Both return the same value true or false if an object is created with literal syntax. No difference
const student = { name: 'abc' };
console.log(Object.hasOwn(student, 'name'));// true
console.log(Object.hasOwn(student, 'id'));// false
console.log(student.hasOwnProperty('name'));// true
console.log(student.hasOwnProperty('id'));// false
Next, Create an Object using Object.create(null)
syntax throws an error
hasOwn
returns true
hasOwnProperty
throws an error.
This is the main difference between using hasOwn
over hasOwnProperty
method
let employee = Object.create(null);
employee.id = 35;
console.log(Object.hasOwn(student, 'id'));// true
console.log(employee.hasOwnProperty('id'));// Error: employee.hasOwnProperty is not a function