Sub topic 10
Checking for Private Fields with #field in obj
This chapter assumes you know ES2015 classes, how instanceof and prototypes work, and the private field syntax covered in the earlier chapter on private fields.
Reading a private field such as obj.#count on an object that lacks it throws a TypeError. That makes it awkward to ask "is this object a real instance of my class?" The #field in obj syntax, added in ES2022, answers that question with a boolean and never throws for a missing field. The check is called a brand check. The private field acts as a brand that only the class constructor can attach to an object.
The basic syntax
The left side is a private name declared in the enclosing class. The right side is any object. The expression is true if that exact private field was installed on the object, and false otherwise.
class Counter {
#count = 0;
static isCounter(obj) {
return #count in obj;
}
}
class Sub extends Counter {}
console.log(Counter.isCounter(new Counter())); // true
console.log(Counter.isCounter(new Sub())); // true: Counter's constructor ran
console.log(Counter.isCounter({ count: 0 })); // falseThe check only works inside the class body that declares #count. Writing #count in obj anywhere else is a SyntaxError, just like reading obj.#count would be.
Why not instanceof?
instanceof walks the prototype chain. Anyone can build an object with the right prototype and never run the constructor, so the object never receives its private fields. Calling a method that reads those fields then throws.
class Counter {
#count = 0;
increment() {
this.#count++;
return this.#count;
}
static isCounter(obj) {
return #count in obj;
}
}
const fake = Object.create(Counter.prototype);
console.log(fake instanceof Counter); // true
console.log(Counter.isCounter(fake)); // false
try {
fake.increment();
} catch (err) {
console.log(err instanceof TypeError); // true: fake has no #count
}| Check | What it tests | Can be faked? |
|---|---|---|
| `obj instanceof C` | `C.prototype` is on the prototype chain | Yes, with `Object.create` or `Symbol.hasInstance` |
| `#field in obj` | The constructor installed `#field` on this object | No |
Brand checks also work across realms. An instance created in an iframe fails instanceof against the main window's class, but a brand check runs on the field itself and does not consult the prototype chain.
How the expression is evaluated
The TypeError for non-objects catches many people out. #count in 5 and #count in null both throw, the same as 'x' in 5. If the input could be a primitive, guard it first.
A practical use: safe equality
An equals method should return false for a foreign value instead of crashing:
class Money {
#cents;
constructor(cents) {
this.#cents = cents;
}
equals(other) {
return (
typeof other === 'object' &&
other !== null &&
#cents in other &&
this.#cents === other.#cents
);
}
}
const a = new Money(500);
console.log(a.equals(new Money(500))); // true
console.log(a.equals({ cents: 500 })); // false
console.log(a.equals(null)); // false
console.log(a.equals(42)); // falseThe older try/catch approach
Before ES2022, the usual workaround was to read the field and catch the error:
class Counter {
#count = 0;
static isCounter(obj) {
try {
obj.#count;
return true;
} catch {
return false;
}
}
}
console.log(Counter.isCounter(new Counter())); // true
console.log(Counter.isCounter({})); // falseThis works for plain fields, but it is wordy. It is also wrong for private accessors. If you check obj.#total where #total is a private getter, the getter actually runs, and any error it throws for its own reasons gets reported as "not an instance." The in form never runs a getter or a method. It only checks whether the name is present.
Exercise
Given class Token { #id = 1; static is(x) { return #id in x; } }, what does each call produce: Token.is(new Token()), Token.is(Object.create(Token.prototype)), and Token.is(undefined)?
Show answer
true, then false (the constructor never ran, so #id was never installed), then a thrown TypeError, because the right side of in must be an object.
Exercise
Why is #total in obj a better check than try { obj.#total; return true } catch { return false } when #total is a private getter?
Show answer
The try/catch version runs the getter. If the getter throws for some other reason, the check wrongly returns false and hides the real error. The in form only checks whether the private name is present and never calls the getter.