JS: “in” Operator

By Xah Lee. Date: .

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.

[see JS: Symbol Tutorial]

// check if a property is in prototype chain

const o1 = {"p1":1};

// create a object o2, with parent o1
const o2 = Object.create(o1);

o2["p2"] = 2;

console.log("p1" in o2); // true
console.log("p2" in o2); // true

Example with symbol key:

// the “in” operator works with both string and symbol keys

const sy = Symbol();

const ob = {};
ob["st"] = 3; // add a string key
ob[sy] = 4;   // add a symbol key

console.log( "st" in ob ) // true
console.log( sy in ob ) // true

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

Note, you can also use Reflect.has(obj, key) [see JS: Reflect.has]

JS Object Property Topic

  1. JS: Property Overview
  2. JS: Property Key
  3. JS: Property Dot Notation / Bracket Notation
  4. JS: Create/Delete Property
  5. JS: Get Property, Set Property
  6. JS: Check Property Existence
  7. JS: Access Property
  8. JS: Property Attributes, writable, enumerable, configurable
  9. JS: Getter/Setter Properties
  10. JS: Property Descriptor
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Patreon me $5. Ask me question on patreon