Object.hasOwnProperty()
is used in JavaScript to check if an object has a specific property as its own—not something inherited from another object.
Contents
Key takeaway
hasOwnProperty()
is useful for distinguishing between properties that belong to the object and those that come from its prototype or inheritance.
Example
let person = {
name: 'John',
age: 30
};
console.log(person.hasOwnProperty('name')); // true
console.log(person.hasOwnProperty('gender')); // false
- What it does: It checks if the
person
object has a property called ‘name’ or ‘gender.’ - True result: If the property exists directly in the object (like ‘name’ in this example), it returns
true
. - False result: If the property doesn’t exist or is inherited, it returns
false
.
It’s a way to confirm if a property really belongs to the object you’re working with, not something from its prototype or parent objects.
Here are a few more examples to help clarify how Object.hasOwnProperty()
works:
Example 1: Direct property check
let book = {
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald'
};
console.log(book.hasOwnProperty('title')); // true
console.log(book.hasOwnProperty('publisher')); // false
- The
book
object has atitle
property, so it returnstrue
. - It doesn’t have a
publisher
property, so it returnsfalse
.
Example 2: Checking inherited properties
function Animal(name) {
this.name = name;
}
Animal.prototype.species = 'Mammal';
let dog = new Animal('Buddy');
console.log(dog.hasOwnProperty('name')); // true
console.log(dog.hasOwnProperty('species')); // false
- The
dog
object has its ownname
property, so it returnstrue
. species
is inherited from the prototype (Animal.prototype
), sohasOwnProperty()
returnsfalse
.
Example 3: Using in loops with hasOwnProperty()
Sometimes when you loop through object properties, you might want to filter out inherited ones. Here’s how hasOwnProperty()
helps:
let car = {
make: 'Honda',
model: 'Civic'
};
for (let prop in car) {
if (car.hasOwnProperty(prop)) {
console.log(prop + ': ' + car[prop]);
}
}
- This loop prints only the properties that belong directly to the
car
object (make
andmodel
).
Example 4: Using with inherited methods
let person = {
name: 'Alice'
};
console.log(person.hasOwnProperty('toString')); // false
console.log(person.hasOwnProperty('name')); // true
toString
is an inherited method, sohasOwnProperty()
returnsfalse
.name
is a direct property ofperson
, so it returnstrue
.