The in operator checks if a property exists in an object or its prototype chain. It returns true if the property is found, and false if not. Important: it checks for property existence, not its value.
const user = { name: 'John' };
console.log('name' in user); // true
console.log('age' in user); // falseThe [in] operator is a way to check if an object has a property. It’s different from other checking methods and has its own features.
Checks for property existence in object and its prototypes:
const user = { name: 'John' };
console.log('name' in user); // true
console.log('age' in user); // falseconst obj = {
value: undefined,
missing: undefined // Actually property doesn't exist
};
console.log('value' in obj); // true — property exists
console.log('missing' in obj); // false — property doesn't existconst user = { name: 'John', age: 25 };
if ('name' in user) {
console.log('Name exists'); // Will trigger
}
if ('phone' in user) {
console.log('Phone exists'); // Won't trigger
}const obj = {};
// All objects have inherited methods
console.log('toString' in obj); // true
console.log('hasOwnProperty' in obj); // trueconst parent = { inherited: 'value' };
const child = Object.create(parent);
console.log('inherited' in child); // true — through prototypeconst user = { name: 'John' };
const key = 'name';
console.log(key in user); // trueconst obj = { value: undefined };
// ❌ Doesn't work properly
if (obj.value) { /* won't trigger */ }
// ✅ Correct
if ('value' in obj) { /* will trigger */ }const arr = [1, 2, 3];
// Check if array method exists
if ('push' in arr) {
console.log('Can use push'); // Will trigger
}const obj = { name: 'John' };
// ❌ Checks only own properties
console.log(obj.hasOwnProperty('toString')); // false
// ✅ Checks everything, including inherited
console.log('toString' in obj); // trueconst obj = { value: undefined };
// ❌ Doesn't distinguish undefined from missing property
if (obj.value === undefined) { /* doesn't distinguish cases */ }
// ✅ Properly checks existence
if ('value' in obj) { /* knows exactly if property exists */ }The [in] operator is convenient when you need to know exactly if an object has a property, regardless of its value.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪