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); // falseInherited 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); // trueIf 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 ownedArrays: 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 valueQuick guide
- Use
into check a property name or array index. - Remember that inherited properties can return
true. - Use
Object.hasOwn()for an own-property check. - Use
includes()when you want to search for an array value.