The Object hasOwnProperty() method

By

Learn how the JavaScript hasOwnProperty() method checks if an object has a property of its own, returning true or false for the property name you pass in.

~~~

The hasOwnProperty() method tells you if an object has a property of its own, with the name you pass as argument. It returns true if the property exists directly on the object, false otherwise.

Example:

const person = { name: 'Fred', age: 87 }
person.hasOwnProperty('name') //true
person.hasOwnProperty('job') //false

Why “own” matters

Objects in JavaScript inherit properties from their prototype. Every plain object gets methods like toString() from Object.prototype, even if you never defined them.

hasOwnProperty() ignores those inherited properties. It only looks at the object itself:

const person = { name: 'Fred', age: 87 }

'toString' in person //true
person.hasOwnProperty('toString') //false

The in operator walks the whole prototype chain. hasOwnProperty() does not. That’s the difference between the two.

This is why you often see it inside a for...in loop, which also iterates over inherited enumerable properties:

for (const key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key)
  }
}

The check filters out anything coming from the prototype, so you only handle the object’s own properties. With plain object literals the filter changes nothing, but it protects you when some code added properties to the prototype.

Notice that a property set to undefined still counts as an own property:

const person = { name: undefined }
person.hasOwnProperty('name') //true

The property exists. Its value happens to be undefined.

When hasOwnProperty() fails

The method lives on Object.prototype, and objects normally inherit it from there. But not all objects do. An object created with Object.create(null) has no prototype at all, so calling the method on it throws:

const scores = Object.create(null)
scores.math = 9

scores.hasOwnProperty('math') //TypeError

You hit the same problem when an object defines its own property named hasOwnProperty. That property shadows the inherited method, and calling it does something else entirely. This matters when the object holds external data, like a parsed JSON payload, where any key can appear.

The fix is Object.hasOwn(), a static method added in ES2022 that performs the same check on any object:

Object.hasOwn(scores, 'math') //true

My advice is to prefer Object.hasOwn() when you can use it. It does exactly what hasOwnProperty() does, without depending on the object’s prototype chain.

~~~

Related posts about js: