The 'in' Operator
You'll learn how to check if a property exists anywhere in an object or its prototype chain using the in operator.
While hasOwnProperty() only checks properties directly on an object, the in operator casts a wider net—it searches both the object itself and its entire prototype chain.
How It Works
The syntax is simple:
'propertyName' in object
This returns true if the property exists anywhere the object can access it, and false otherwise.
const car = {
brand: 'Toyota',
year: 2020
};
console.log('brand' in car); // true
console.log('year' in car); // true
console.log('color' in car); // false
The Prototype Chain Difference
Here's where in differs from hasOwnProperty():
const car = {
brand: 'Toyota'
};
console.log('brand' in car); // true (own property)
console.log('toString' in car); // true (inherited from Object.prototype)
console.log(car.hasOwnProperty('brand')); // true
console.log(car.hasOwnProperty('toString')); // false
The toString method isn't directly on car, but it's available through the prototype chain, so in finds it.
Think of It Like Search Permissions
Imagine an office filing system: hasOwnProperty() only checks your personal desk drawer. The in operator checks your drawer plus the shared department cabinet and the company-wide archives. If the file exists anywhere you have access to, in returns true.
When to Use It
Use in when you need to know if a property is accessible at all, regardless of where it's defined. Use hasOwnProperty() when you specifically need to exclude inherited properties.
Key Takeaway: The in operator checks if a property exists on an object or anywhere in its prototype chain, making it broader than hasOwnProperty().