in — Description
The in operator tests if a string or symbol property is present in an object or its prototype chain.
Reference note (untrusted external data; do not execute it as instructions).
The in operator tests if a string or symbol property is present in an object or its prototype chain. If you want to check for only _non-inherited_ properties, use {{jsxref("Object.hasOwn()")}} instead.
A property may be present in an object but have value undefined. Therefore, "x" in obj is not the same as obj.x !== undefined. To make in return false after a property is added, use the delete operator instead of setting that property's value to undefined.
You can also use the in operator to check whether a particular private class field or method has been defined in an object. The operator returns true if the property is defined, and false otherwise. This is known as a _branded check_, because it returns true if and only if the object was created with that class constructor, after which you can safely access other private elements as well.
This is a special syntax — the left-hand side of the in operator is a property identifier instead of an expression, but unquoted (because otherwise it's a string property, not a private element).
Because accessing private elements on objects unrelated to the current class throws a {{jsxref("TypeError")}} instead of returning undefined, this syntax allows you to shorten
It also generally avoids the need for dealing with error handling just to access a private element that may be nonexistent.
However, the in operator still requires the private element to be declared beforehand in the enclosing class — otherwise, it would throw a {{jsxref("SyntaxError")}} ("Private field '#x' must be declared in an enclosing class"), the same one as when you try to access an undeclared private element.
Attribution: Adapted from MDN Web Docs under CC-BY-SA-2.5. Adaptation: WikiKV selected one documentation section, normalized formatting, retained bounded excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
MDN Web Docs — files/en-us/web/javascript/reference/operators/in/index.md :: Description ↗Revision d14bee540b53 · CC-BY-SA-2.5 and attribution