The JavaScript in operator
By Flavio Copes
Learn how the JavaScript in operator checks whether an object has a property, including properties inherited from its ancestors in the prototype chain.
The in operator is pretty useful. It allows us to check if an object has a property.
This operator returns true if the first operand is a property of the object passed on the right, or a property of one of its ancestors in its prototype chain.
Otherwise it returns false.
Example:
class Car {
constructor() {
this.wheels = 4
}
}
class Fiesta extends Car {
constructor() {
super()
this.brand = 'Ford'
}
}
const myCar = new Fiesta()
'brand' in myCar //true
'wheels' in myCar //true
wheels is defined by the parent class, and in still finds it. That’s the prototype chain lookup at work.
Why not just check the value?
You might wonder why we don’t just check myCar.brand !== undefined. The problem is that a property can exist and hold undefined as its value:
const person = { age: undefined }
person.age !== undefined //false, looks missing
'age' in person //true, it's there
The in operator tells you if the property exists, regardless of its value. That distinction matters when undefined is a legitimate value in your data.
Once you delete a property, in correctly reports it gone:
delete person.age
'age' in person //false
It also finds inherited built-ins
Since in walks the whole prototype chain, it returns true for methods every object inherits:
'toString' in myCar //true
If you only care about properties defined directly on the object, use Object.hasOwn() instead:
Object.hasOwn(myCar, 'brand') //true
Object.hasOwn(myCar, 'toString') //false
Be careful with arrays
Here’s the pitfall I see most often. Used on an array, in checks the indexes, not the values:
const colors = ['red', 'blue']
'red' in colors //false
0 in colors //true
2 in colors //false
It looks like it should tell you whether 'red' is in the array. It doesn’t, because array indexes are the property names.
To check if an array contains a value, use includes():
colors.includes('red') //true
One last note: the left operand must be a property name, a string or a symbol (numbers get converted to strings). The right operand must be an object, using in on a plain string or number throws a TypeError.
Related posts about js: