JavaScript

This page explains how the JavaScript in operator checks for a property name on an object or an index on an array.

Goal: distinguish checking for a key from searching for a value, and understand that inherited properties can also match.

The in operator

Use the form "propertyName" in object to ask whether an object has a property with that name. The result is true or false.

JavaScript

const user = { name: "Taro", age: 20 };

console.log("name" in user);  // true
console.log("email" in user); // false

Inherited properties also match

Objects can inherit properties through their prototype. The in operator checks the object and its prototype chain, so common inherited names can return true.

JavaScript

console.log("toString" in user); // true

If you only want a property directly owned by the object, use Object.hasOwn().

JavaScript

const user = Object.create({ shared: true });
user.name = "Taro";

"shared" in user;              // true: inherited
Object.hasOwn(user, "shared"); // false: not directly owned

Arrays: indexes, not values

With an array, in checks whether an index exists. It does not check whether a value appears in the array.

JavaScript

const data = ["A", "B"];

0 in data; // true
2 in data; // false
data.includes("B"); // true: search for a value

Quick guide

Related topics