JavaScript .hasOwn()

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

  • A full-stack engineer can get a project done from start to finish, back-end to front-end.
    • Includes 51 Courses
    • With Professional Certification
    • Beginner Friendly.
      150 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

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

Contribute to Docs

Learn JavaScript on Codecademy

  • A full-stack engineer can get a project done from start to finish, back-end to front-end.
    • Includes 51 Courses
    • With Professional Certification
    • Beginner Friendly.
      150 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours