Tips

Object has a property?

1. hasOwnProperty()

The hasOwnProperty() method is the most direct way to determine if an object has a specific property as its own property (as opposed to inheriting it from its prototype chain).

const obj = { name: "Alice", age: 25 };
console.log(obj.hasOwnProperty('name')); // true
console.log(obj.hasOwnProperty('gender')); // false

2. The in operator

The in operator checks whether a property exists in an object or its prototype chain. This is broader than hasOwnProperty(), as it includes inherited properties.

const obj = { name: "Alice", age: 25 };
console.log('name' in obj); // true
console.log('toString' in obj); // true (because toString is an inherited property)

3. Property Access

You can simply try to access the property and check if it is undefined. However, this method can give false negatives if the property exists but its value is explicitly set to undefined.

const obj = { name: "Alice", age: undefined };
console.log(obj.age !== undefined); // false, but the property does exist
console.log(obj.gender !== undefined); // false

4. Object.keys() or Object.getOwnPropertyNames()

You can use Object.keys() or Object.getOwnPropertyNames() to get an array of an object's own property names (ignoring the prototype chain for Object.keys() and including non-enumerable properties for Object.getOwnPropertyNames()), and then check if the property name is in that array.

const obj = { name: "Alice", age: 25 };
console.log(Object.keys(obj).includes('name')); // true
console.log(Object.getOwnPropertyNames(obj).includes('gender')); // false

5. Reflect.has()

Reflect.has() method works similarly to the in operator but is designed as a function that can be used with Reflect API semantics.

const obj = { name: "Alice", age: 25 };
console.log(Reflect.has(obj, 'name')); // true
console.log(Reflect.has(obj, 'toString')); // true

Summary

  • Use hasOwnProperty() if you need to check whether an object has a property without looking up the prototype chain.
  • Use in operator if you also want to consider properties inherited from the prototype.
  • Use Object.keys() or Object.getOwnPropertyNames() for a list-based approach to checking properties.
  • Use Reflect.has() if you prefer the Reflect API or need to consider prototype properties as well.
  • Checking with property access is simple but can be inaccurate if the property can have a value of undefined.

Each of these methods has its use cases depending on what exactly you need to check in your JavaScript objects. Choose the one that best fits your scenario.

Last Update: 14:48 - 14 April 2024

On this page