.hasOwn()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Jan 4, 2024
Contribute to Docs

The .hasOwn() method verifies if a specific property exists in an object, returning true if present, otherwise false. Unlike the in operator, it solely inspects direct object properties and doesn’t consider inherited ones. This method serves as a replacement for Object.hasOwnProperty().

Syntax

Object.hasOwn(obj, prop)
  • Obj: The Javascript object instance to test.
  • prop: It is the property on which the check is to be applied.

Example 1

The following code will check whether the given object has specific properties.

let details = {
name: 'Jack',
course: 'Javascript Foundation',
};
// Check if 'details' object has its own property named 'name'
console.log(Object.hasOwn(details, 'name'));
// Check if 'details' object has its own property named 'course'
console.log(Object.hasOwn(details, 'course'));
// Check if 'details' object has its own property named 'phone number'
console.log(Object.hasOwn(details, 'phone number'));

This above example will return the following output:

true
true
false

Example 2

The following example illustrates the differentiation between direct properties and properties inherited through the prototype chain in JavaScript.

let details = {
name: 'Jack',
};
details.age = 25;
// Check if 'details' object has its own property named 'age'
console.log(Object.hasOwn(details, 'age'));
// Check if 'details' object has its own property named 'toString'
console.log(Object.hasOwn(details, 'toString'));

This above example will return the following output:

true
false

All contributors

Looking to contribute?

Learn JavaScript on Codecademy