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

  1. Property Overview
  2. Property Key
  3. Dot vs Bracket Notation
  4. Create/Delete Property
  5. Get/Set Property
  6. Property Existence
  7. Access Property
  8. List Properties
  9. Property Attributes
  10. Getter/Setter
  11. Property Descriptor
  12. Symbol
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials