How do you check if an object has a property?

JavaScript

The short answer

The three main ways are the in operator (checks own and inherited properties), hasOwnProperty() (checks only own properties), and Object.hasOwn() (the modern replacement for hasOwnProperty). You can also use !== undefined, but it fails for properties that are explicitly set to undefined.

The methods

const user = { name: 'John', age: undefined };
// in operator — checks own + inherited properties
'name' in user; // true
'age' in user; // true
'toString' in user; // true — inherited from Object.prototype
// hasOwnProperty — checks only own properties
user.hasOwnProperty('name'); // true
user.hasOwnProperty('toString'); // false — inherited
// Object.hasOwn (modern, recommended)
Object.hasOwn(user, 'name'); // true
Object.hasOwn(user, 'toString'); // false
// !== undefined — breaks for properties set to undefined
user.name !== undefined; // true
user.age !== undefined; // false — but the property EXISTS!

Which to use

  • Object.hasOwn(obj, key) — the best choice for modern code. Checks own properties only.
  • 'key' in obj — when you also want to check inherited properties.
  • obj.hasOwnProperty(key) — the older way. Works fine but Object.hasOwn is safer (it works even if hasOwnProperty has been overridden on the object).

Why Object.hasOwn is better

// Edge case: object with no prototype
const obj = Object.create(null);
obj.name = 'John';
obj.hasOwnProperty('name'); // TypeError — hasOwnProperty does not exist!
Object.hasOwn(obj, 'name'); // true — works fine

Object.hasOwn is a static method that always works, regardless of the object's prototype.

Interview Tip

Show all three methods and explain the difference between own and inherited properties. Recommending Object.hasOwn() as the modern best practice shows you are up to date. The age: undefined edge case is a good detail that catches candidates off guard.

Why interviewers ask this

This tests fundamental object knowledge. Interviewers want to see if you know the difference between own and inherited properties, and if you can handle edge cases like properties set to undefined.