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.
// 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 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, you can also use Reflect.has( obj, key) [see Reflect.has]

JS in Depth