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.
key in object #privateField in object
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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 objistruefor{ x: undefined }. Useobj.x !== undefinedif 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:
intests indexes (keys), not values. Useincludes()to look for a value. Holes in sparse arrays givefalse. - Don't write
inin a for-loop head by accident: infor (x in obj)it's thefor...instatement, which loops over enumerable keys, not an operator. - Proxies: the
hastrap interceptsin, which lets a proxy hide or invent keys. - Dictionaries: for lookup tables with arbitrary keys, prefer
MaporObject.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.