JavaScript: “in” Operator

By Xah Lee. Date: . Last updated: .
key in obj
Return true if property key key is obj's own property or if key is a property of some object in obj's prototype chain. (Both string and Symbol keys) Else, false.

simple example:

const x1 = {"p1":1};
console.log("p1" in x1); // true

Example showing parent property:

// an object
const x1 = {"p1":1};

// create a object x2, with parent x1
const x2 = Object.create(x1);

console.log("p1" in x2); // true
// true because p1 is a property of x2's parent

Example with symbol key:

// the “in” operator works with symbol key
const sy = Symbol();
const x1 = {[sy]:4};
console.log( sy in x1 ); // true

Note: the syntax key in obj is not a part of the syntax for (key in obj) {}. They look the same but don't have the same meaning. [see for-in Loop]

Note, a functional form of in-operator is Reflect.has. [see Reflect.has]

[see Access Property]

JavaScript Check Property Existence

BUY
ΣJS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc