Object.hasOwn()

Checks whether an object has its own property with the given name.

Returns
true or false.
Changes the original
No
On this page

Example

#
JavaScript
const profile = { name: 'Mia', bio: undefined }

console.log(Object.hasOwn(profile, 'bio'))
console.log(Object.hasOwn(profile, 'toString'))
console.log('toString' in profile)
Console
true
false
true

Definition and usage

#

The Object.hasOwn(obj, key) method returns true if the object has a property with that name directly on it, not inherited from the prototype. It’s a more modern and safer equivalent of obj.hasOwnProperty(key).

It differs from the in operator, which also checks inherited properties. For example, "toString" in {} returns true, while Object.hasOwn({}, "toString") returns false.

It also works on objects without a prototype (created with Object.create(null)), where the hasOwnProperty method doesn’t exist at all.

Syntax

#
Syntax
Object.hasOwn(obj, prop)

Parameters

#
  • obj

    object

    The object being checked.
  • prop

    string or symbol

    The property name.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Checking with if (obj.field) can’t tell a missing field apart from a value of 0, "", or undefined. Object.hasOwn() can.
  • In new code, replace hasOwnProperty with Object.hasOwn().

Related entries

#

Spotted a mistake or missing an example? Write to us.