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
falseThe 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
trueWhy 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
trueCommon 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 ageFunctions 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.