0
0
JavascriptHow-ToBeginner · 3 min read

How to Check if Property Exists in Object in JavaScript

To check if a property exists in an object in JavaScript, use the in operator like 'property' in object or the hasOwnProperty() method like object.hasOwnProperty('property'). The in operator checks all properties including inherited ones, while hasOwnProperty() checks only own properties.
📐

Syntax

There are two main ways to check if a property exists in an object:

  • Using in operator: Checks if the property exists anywhere in the object or its prototype chain.
  • Using hasOwnProperty() method: Checks if the property exists directly on the object itself, not inherited.
javascript
'propertyName' in object
object.hasOwnProperty('propertyName')
💻

Example

This example shows how to use both in and hasOwnProperty() to check for properties in an object.

javascript
const car = {
  make: 'Toyota',
  model: 'Corolla'
};

console.log('make' in car); // true
console.log(car.hasOwnProperty('model')); // true
console.log('year' in car); // false
console.log(car.hasOwnProperty('toString')); // false because toString is inherited
console.log('toString' in car); // true because it's inherited
Output
true true false false true
⚠️

Common Pitfalls

One common mistake is using hasOwnProperty() on objects that might not inherit from Object.prototype, which can cause errors. Also, in returns true for inherited properties, which might be unexpected.

To avoid errors, use Object.prototype.hasOwnProperty.call(object, property) if unsure.

javascript
const obj = Object.create(null); // no prototype
obj.name = 'Alice';

// This will cause error if obj has no hasOwnProperty method
// console.log(obj.hasOwnProperty('name')); // Error

// Safe way:
console.log(Object.prototype.hasOwnProperty.call(obj, 'name')); // true
Output
true
📊

Quick Reference

MethodChecks Own Property?Includes Inherited?Example Usage
in operatorNoYes'property' in object
hasOwnProperty()YesNoobject.hasOwnProperty('property')
Safe hasOwnPropertyYesNoObject.prototype.hasOwnProperty.call(object, 'property')

Key Takeaways

Use the 'in' operator to check if a property exists anywhere in the object or its prototype chain.
Use 'hasOwnProperty()' to check only own properties of the object.
Avoid errors on objects without prototypes by using Object.prototype.hasOwnProperty.call().
Remember 'in' returns true for inherited properties, which may not always be desired.
Checking property existence helps avoid errors when accessing undefined properties.