Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Operators

The in operator

Reference for the JavaScript in operator: testing for properties and array indexes, inherited properties, private brand checks and for...in differences.

The in operator checks whether an object has a property with a given key, including inherited properties. The key can be a string or a symbol, and the result is a boolean. It looks only at existence, not at the value, so a property whose value is undefined still counts.

JavaScript
key in object
#privateField in object

Try it

JS Own and inherited properties

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Sparse arrays, errors and private fields

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
prop in object
#priv in object
Operand Description
prop A string, number or symbol, converted to a property key (numbers become strings).
object The object to search. It must be an object, not a primitive.
#priv A private field, method or accessor name, available inside the class body.

Return value: true if the property exists on the object or anywhere up its prototype chain, otherwise false.

Exceptions: a TypeError if the right side is a primitive (such as a string, number or null). With #priv, a TypeError if the right side is not an object.

Usage notes

  • Existence, not value. "x" in obj is true for { x: undefined }. Use obj.x !== undefined if you only care about meaningful values.
  • Own vs inherited: use Object.hasOwn(obj, key) when inherited properties must not count (for example, so "constructor" in {} doesn't surprise you).
  • Arrays: in tests indexes (keys), not values. Use includes() to look for a value. Holes in sparse arrays give false.
  • Don't write in in a for-loop head by accident: in for (x in obj) it's the for...in statement, which loops over enumerable keys, not an operator.
  • Proxies: the has trap intercepts in, which lets a proxy hide or invent keys.
  • Dictionaries: for lookup tables with arbitrary keys, prefer Map or Object.create(null), so inherited names don't collide.
  • Private brand checks (#x in obj) are the reliable way to ask "was this object built by my class constructor?".

Browser support

Supported in every browser and runtime. The private-field form (#name in object) is newer (ES2022), so check a compatibility table for older targets.