Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if an object has a property

Short answer

Object.hasOwn() checks whether an object has its own property:

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

Output:

true
false

The in operator

The in operator also counts inherited properties, such as built-in methods:

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

Output:

true
true

Why not compare with undefined

A property may exist and still hold undefined — then the comparison gives the wrong answer:

const settings = { theme: undefined };
 
console.log(settings.theme !== undefined);
console.log(Object.hasOwn(settings, 'theme'));

Output:

false
true

Common mistake

A check like if (user.age) treats a property with the value 0, false or an empty string as missing:

const user = { name: 'Anna', age: 0 };
 
console.log(user.age ? 'has age' : 'no age');
console.log(Object.hasOwn(user, 'age') ? 'has age' : 'no age');

Output:

no age
has age

Functions used in this recipe

  • Object.hasOwn — Checks whether an object has its own property.
  • Object.keys — Returns an array of an object's property names.

Thanks for reading!

Donate to the site — we work hard for you.