The JavaScript in operator

By

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