Sub topic 10
Checking for Private Fields with #field in obj
This chapter assumes you already know how to declare private fields, private methods, and static private members with the # syntax. You should also understand prototypes and how instanceof works. It covers the ergonomic brand check, #field in obj, which was added in ES2022. With it, you can ask whether an object really holds a given private field without risking a TypeError.
What a Brand Check Is
A brand check asks whether an object was really built by a particular class. It is a different question from whether the object looks like an instance or has the right prototype. Private fields work well as brands. The class constructor stamps them onto each object, and code outside the class body cannot add, remove, or fake them.
There is one catch. Reading a private field on an object that lacks it throws a TypeError, so obj.#x can't tell you whether obj has #x. The in operator solves this. You put a private name on the left, and the expression returns true or false:
class Point {
#x;
#y;
constructor(x, y) {
this.#x = x;
this.#y = y;
}
static isPoint(obj) {
return #x in obj;
}
}
console.log(Point.isPoint(new Point(1, 2))); // true
console.log(Point.isPoint({ x: 1, y: 2 })); // falseThe #x on the left is the private name itself. It is not a string and it is not a value. Code can write #x in obj only inside the class body that declares #x, the same as any other use of #x.
The Old Way: try/catch
Before ES2022, the only way to test for a private field was to read it and catch the error:
class Point {
#x;
constructor(x) {
this.#x = x;
}
static isPoint(obj) {
try {
obj.#x;
return true;
} catch {
return false;
}
}
}
console.log(Point.isPoint(new Point(3))); // true
console.log(Point.isPoint({})); // false
console.log(Point.isPoint(null)); // falseThis works for a plain field, but it has real problems:
- It is verbose and hides what the code means.
- It breaks with private accessors. If
#xis a private getter,obj.#xruns the getter. A getter that throws for its own reasons then looks like "not a Point". - A getter with side effects runs during what should be a read-only check.
#x in obj never reads the value or runs a getter. It only checks whether the private name is present.
How the Check Is Evaluated
The diagram shows three rules worth remembering:
- The right side must be an object.
#x in 42,#x in 'str',#x in null, and#x in undefinedall throw aTypeError, the same as'x' in 42. - The check looks only at the object itself. Private names are never inherited through the prototype chain.
- Proxies are not transparent. A Proxy is a separate object that holds no private names, and no handler trap is called.
Brand Checks vs instanceof
instanceof walks the prototype chain looking for Class.prototype. Anyone can manipulate that chain, so instanceof gives a weaker guarantee:
class Token {
#secret = Math.random();
static isToken(obj) {
return #secret in obj;
}
}
// A fake that has the right prototype but was never constructed
const fake = Object.create(Token.prototype);
console.log(fake instanceof Token); // true
console.log(Token.isToken(fake)); // false
// A real instance whose prototype was swapped
const real = new Token();
Object.setPrototypeOf(real, Object.prototype);
console.log(real instanceof Token); // false
console.log(Token.isToken(real)); // trueinstanceof can also be changed with Symbol.hasInstance. The brand check cannot be changed from outside the class.
| Technique | What it tests | Can outside code fake it? | Throws on primitives? | Runs getters? |
|---|---|---|---|---|
| `obj instanceof C` | `C.prototype` is on the prototype chain | Yes (`Object.create`, `setPrototypeOf`, `Symbol.hasInstance`) | No, returns `false` | No |
| `try { obj.#x } catch {}` | Reading `#x` succeeds | No | No, the error is caught | Yes, for private accessors |
| `#x in obj` | `obj` holds private name `#x` | No | Yes, `TypeError` | No |
Use instanceof for everyday type dispatch, where duck typing is acceptable. Use a brand check when your code is about to read private state from an object it did not create, such as in equals, compare, or static factory helpers.
A Practical Use: Safe equals
Methods that take "another instance" as an argument are the most common place for brand checks. If you read other.#x without checking first, the method throws on bad input:
class Money {
#cents;
#currency;
constructor(cents, currency) {
this.#cents = cents;
this.#currency = currency;
}
equals(other) {
if (!Money.#isMoney(other)) return false;
return this.#cents === other.#cents && this.#currency === other.#currency;
}
static #isMoney(value) {
return (typeof value === 'object' || typeof value === 'function')
&& value !== null
&& #cents in value;
}
}
const a = new Money(500, 'EUR');
console.log(a.equals(new Money(500, 'EUR'))); // true
console.log(a.equals({ cents: 500 })); // false
console.log(a.equals(500)); // false, no TypeError
console.log(a.equals(null)); // falseThe typeof guard is required because #cents in 500 throws. Putting the full check in a private static helper keeps every public method short and consistent.
Syntax Rules and Gotchas
The name must be declared in an enclosing class
A brand check that uses a private name the enclosing class doesn't declare is an early SyntaxError. The script fails to parse, so not even its first line runs:
class A {
#a;
static check(obj) {
return #a in obj; // fine
// return #b in obj; // SyntaxError: #b is not declared
}
}
console.log(A.check(new A())); // trueNested classes can use the outer class's private names, because the names are lexically scoped:
class Outer {
#id = 1;
static makeChecker() {
return class Inner {
static test(obj) {
return #id in obj; // refers to Outer's #id
}
};
}
}
const Checker = Outer.makeChecker();
console.log(Checker.test(new Outer())); // true
console.log(Checker.test({})); // falseNegation needs parentheses
#x cannot be used as a value on its own, so !#x in obj is a SyntaxError. Write !(#x in obj) instead:
class Guarded {
#ok = true;
static assert(obj) {
if (!(#ok in obj)) {
throw new TypeError('Not a Guarded instance');
}
return true;
}
}
console.log(Guarded.assert(new Guarded())); // true
try {
Guarded.assert({});
} catch (err) {
console.log(err.message); // 'Not a Guarded instance'
}Methods and accessors work too
Private methods and private accessors are installed on every instance during construction, so you can check for them the same way:
class Widget {
#render() { return '<widget>'; }
get #label() { return 'w'; }
static check(obj) {
return [#render in obj, #label in obj];
}
}
console.log(Widget.check(new Widget())); // [ true, true ]
console.log(Widget.check({})); // [ false, false ]The check for #label does not call the getter.
Subclass instances pass, subclass constructors do not
A subclass instance passes the base class's brand check, because super() runs the base constructor, and that constructor installs the base class's private fields. Static private fields are different. They exist only on the class that declares them, not on subclasses:
class Base {
#tag = 'base';
static #registry = [];
static isBase(obj) {
return #tag in obj;
}
static hasRegistry(cls) {
return #registry in cls;
}
}
class Child extends Base {}
console.log(Base.isBase(new Child())); // true
console.log(Base.hasRegistry(Base)); // true
console.log(Base.hasRegistry(Child)); // falseThe last line is a common surprise. If a static method uses this.#registry and gets called as Child.someMethod(), it throws, because this is Child. A brand check on this lets you detect that case. You can also reference Base.#registry directly.
Proxies fail the check
class Box {
#v = 1;
static isBox(obj) {
return #v in obj;
}
}
const box = new Box();
const proxy = new Proxy(box, {});
console.log(Box.isBox(box)); // true
console.log(Box.isBox(proxy)); // falseThis behavior is consistent. Since reading proxy.#v would throw, reporting false is the honest answer.
Brands belong to objects, not prototypes
If a base constructor returns a different object, the subclass's field initializers run on that object, and the returned object gets branded. This is an obscure pattern, but it shows that the brand lives on whichever object the constructor ends up initializing:
class ReturnsGiven {
constructor(target) {
return target;
}
}
class Stamp extends ReturnsGiven {
#stamped = true;
static has(obj) {
return #stamped in obj;
}
}
const plain = {};
new Stamp(plain);
console.log(Stamp.has(plain)); // true
console.log(Object.keys(plain)); // []
console.log(plain instanceof Stamp); // falseThe object plain now passes the brand check even though its prototype has not changed. In ordinary code this never happens. It is still worth knowing when you rely on brand checks for security-sensitive decisions.
Each class evaluation creates new names
Each time a class declaration or expression is evaluated, it creates new private names. If a factory function returns a new class on every call, each class gets its own #x, and instances of one class fail another class's check. The same applies across realms such as iframes or vm contexts. An object created from another realm's copy of the class does not pass this realm's check.
Exercises
Exercise
A Temperature class declares #kelvin. Its static method isTemperature(obj) returns #kelvin in obj. What do the calls isTemperature(Object.create(Temperature.prototype)), isTemperature(new Proxy(new Temperature(300), {})), and isTemperature(undefined) produce, and why?
Show answer
The first returns false, because Object.create never runs the constructor, so the object never received #kelvin. The second also returns false, because a Proxy is a separate object that holds no private names, and brand checks ignore Proxy traps. The third throws a TypeError, because the right operand of in must be an object.
Exercise
Rewrite this check so it parses and behaves correctly: static notMine(obj) { return !#id in obj; }
Show answer
Write static notMine(obj) { return !(#id in obj); }. The private name #id is not a value on its own, so applying ! to it is a SyntaxError. The parentheses negate the whole brand check. If obj might be a primitive, add a guard such as typeof obj === 'object' && obj !== null first.
Exercise
Class Base declares static #count and a static method bump() that runs this.#count++. Why does Child.bump() throw when Child extends Base, and how could #count in this help?
Show answer
Static private fields exist only on the class that declares them. When bump is called as Child.bump(), this is Child, which has no #count, so reading this.#count throws a TypeError. The method can test #count in this and throw a clearer error. It can also skip the dynamic receiver and reference Base.#count directly.