JS: β€œin” operator πŸ‘Ž

By Xah Lee. Date: . Last updated: .

Checking property existance (key in obj)

key in obj

Return true if property key key is obj's own property or in Prototype Chain. (Both string and Symbol keys) Else, false.

const xx = { "dog": 1 };

console.log("dog" in xx);
// true
console.log("cat" in xx);
// false
// in-operator on parent property

const xdad = { dog: 1 };

// create a object xson, with parent xdad
const xson = Object.create(xdad);

console.log("dog" in xson);
// true
// the in operator works with symbol key
const xx = Symbol();
const yy = { [xx]: 4 };
console.assert(xx in yy);

🟒 tip: better is JS: Reflect.has

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

Checking private field existance (#x in obj)