Checking whether a property exists in an object
1. The in operator - the most universal way
javascript
const user = { name: 'Alice', age: 25 };
console.log('age' in user); // true
console.log('city' in user); // falseChecks whether a key exists in the object (including properties inherited from the prototype).
Example with inheritance:
javascript
const person = { species: 'human' };
const user = Object.create(person);
user.name = 'Alice';
console.log('species' in user); // true (inherited)2. The hasOwnProperty() method - checks only "own" properties
javascript
const user = { name: 'Alice', age: 25 };
console.log(user.hasOwnProperty('age')); // true
console.log(user.hasOwnProperty('city')); // falseUnlike in, it ignores the prototype
and checks only properties actually set on the object itself.
Example of the difference:
javascript
const person = { species: 'human' };
const user = Object.create(person);
user.name = 'Alice';
console.log('species' in user); // true
console.log(user.hasOwnProperty('species')); // false3. Checking against undefined (the simplest, but not always accurate)
javascript
const user = { name: 'Alice' };
if (user.age !== undefined) {
console.log('The age property exists');
} else {
console.log('The age property does not exist');
}Downside: if the property exists, but its value is undefined,
you get a misleading result.
javascript
const user = { age: undefined };
console.log(user.age !== undefined); // false - even though the key exists!4. Object.hasOwn() (a modern alternative to hasOwnProperty)
ES2022 added a safer, more readable way:
javascript
const user = { name: 'Alice' };
console.log(Object.hasOwn(user, 'name')); // true
console.log(Object.hasOwn(user, 'city')); // falseIt works the same way as hasOwnProperty,
but does not depend on possible overrides inside the object.
Summary
| Method | Checks | Considers the prototype | Reliability |
|---|---|---|---|
'key' in obj | whether the property exists | Yes | An excellent choice |
obj.hasOwnProperty('key') | only "own" properties | No | The classic |
Object.hasOwn(obj, 'key') | only "own" properties | No | The modern standard |
obj.key !== undefined | whether the value is not undefined | No | Can give misleading results |
In one phrase:
To check whether a property exists in an object, use
'key' in objif all properties matter (including inherited ones), orObject.hasOwn(obj, 'key')if you need only its own.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.