One of the first topics you’ll come across when learning JavaScript (or any other programming language) are operators.

The most common operators are the arithmetic, logical, and comparison operators. But did you know that JavaScript has an in operator?

If you didn’t, don’t fret. I just came across it recently while searching for a solution to a problem on Google.

In this article, you’ll learn exactly what the JavaScript in operator does, when to use it, and how to use it.

What exactly is the JavaScript in operator?

The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists.

Anatomy of a simple JavaScript object.

The JavaScript prototype chain is how objects or object instances have access to properties and methods that were not originally theirs. These objects inherit properties and methods defined in their constructors or prototypes, which can be accessed through their __proto__ property.

This article assumes that you have a basic understanding of what objects are, how to create them, what they are used for, and how JavaScript inheritance works. If you don’t, this article on MDN should help.

When to use the JavaScript in operator

To verify if a property exists on an object

const car = {
  make: 'Toyota',
  model:'Camry',
  year: '2018',
  start: function() {
    console.log(`Starting ${this.make} ${this.model}, ${this.year}`);
  }
}

'make' in car // Returns true.
'start' in car // Returns true.
'Toyota' in car // Returns false. 'Toyota' is not a property name, but a value.

To verify if a property is inherited by an object.

Let’s use the ES6 class syntax to create an object constructor. This would also apply to function constructors:

class Car {
  constructor(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
  }
  start() {
    console.log(`Starting ${this.make} ${this.model}, ${this.year}`);
  }
}

const toyota = new Car('Toyota', 'Camry', '2018');

'start' in toyota;
/* Returns true as toyota is an instance of the Car object constructor. The toyota object therefore inherits all properties of the Car constructor. */

'toString' in toyota;
/* Returns true. toString is a method property of the Object type, of which the Car constructor is an instance of. */

#javascript #developer

The JavaScript in Operator Explained With Examples
2.20 GEEK