Skip to main content

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); // false

Checks 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')); // false

Unlike 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')); // false

3. 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')); // false

It works the same way as hasOwnProperty, but does not depend on possible overrides inside the object.


Summary

MethodChecksConsiders the prototypeReliability
'key' in objwhether the property existsYesAn excellent choice
obj.hasOwnProperty('key')only "own" propertiesNoThe classic
Object.hasOwn(obj, 'key')only "own" propertiesNoThe modern standard
obj.key !== undefinedwhether the value is not undefinedNoCan give misleading results

In one phrase:

To check whether a property exists in an object, use 'key' in obj if all properties matter (including inherited ones), or Object.hasOwn(obj, 'key') if you need only its own.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.