Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Object.hasOwn

Checks whether an object has its own property.

Available since: ES2022

Syntax

Object.hasOwn(obj, key)

Parameters

ParameterTypeDescription
objobjectThe object to check.
keystring | symbolThe property name.

Return value

booleantrue if the object has its own property with that name.

Examples

Does the property exist:

const user = { name: 'Anna', email: undefined };
 
console.log(Object.hasOwn(user, 'name'));
console.log(Object.hasOwn(user, 'age'));
console.log(Object.hasOwn(user, 'email'));

Output:

true
false
true

The difference from the in operator — inherited properties:

const user = { name: 'Anna' };
 
console.log('toString' in user);
console.log(Object.hasOwn(user, 'toString'));

Output:

true
false

Notes

A property set to undefined still exists, so user.email !== undefined and Object.hasOwn() answer differently. It is the modern replacement for obj.hasOwnProperty(key).

See also

  • in — Checks whether an object has a property (inherited ones included).
  • Object.prototype.hasOwnProperty — Checks whether an object has its own property (the older way).
  • Optional chaining (?.) — Safe property access: returns undefined instead of an error if the object is missing.

Related recipes

In the tutorial

Thanks for reading!

Donate to the site — we work hard for you.