Sub topic 11
Before #: Underscores, Closures, and WeakMaps
Private fields arrived in ES2022. JavaScript developers needed hidden state long before that, and they built it from what the language already had. Those older patterns still appear in libraries, older codebases, and code that has to run where # is unavailable. Some of them can also do things private fields can't.
This chapter assumes you already know closures, the this keyword, ES2015 classes, and the private field syntax from the earlier chapter. You will compare four approaches with # fields: the underscore convention, Symbol keys, closures, and WeakMaps. You will also see which guarantees each one actually gives.
The Underscore Convention
The simplest approach is a naming rule. A leading underscore tells other developers "this is internal, don't touch it." The language does not enforce that rule in any way.
class Thermostat {
constructor(celsius) {
this.celsius = celsius; // goes through the setter
}
get celsius() {
return this._celsius;
}
set celsius(value) {
if (typeof value !== 'number') {
throw new TypeError('celsius must be a number');
}
this._celsius = value;
}
}
const t = new Thermostat(21);
t._celsius = 'hot'; // skips the setter entirely
console.log(t.celsius); // 'hot'
console.log(Object.keys(t)); // [ '_celsius' ]
console.log(JSON.stringify(t)); // '{"_celsius":"hot"}'The setter's validation means nothing here, because any caller can write _celsius directly. The backing property is also an ordinary own data property. It shows up in Object.keys, for...in, spread syntax, JSON.stringify, and debugger output.
The underscore convention does have real uses:
- Subclasses can read and write
_celsiusfreely. Private#fields cannot be reached from subclasses. - Tests and debugging tools can inspect the state without any special access.
- It costs nothing at runtime and works in every engine.
Symbol Keys: Hidden but Reachable
ES2015 symbols gave developers a middle option. A property keyed by a Symbol does not appear in Object.keys, for...in, or JSON.stringify, and nobody can reach it by typing a string name.
const kCelsius = Symbol('celsius');
class Thermostat {
constructor(celsius) {
this[kCelsius] = celsius;
}
get celsius() {
return this[kCelsius];
}
}
const t = new Thermostat(21);
console.log(Object.keys(t)); // []
console.log(JSON.stringify(t)); // '{}'
const [leaked] = Object.getOwnPropertySymbols(t);
t[leaked] = 'hot';
console.log(t.celsius); // 'hot'Object.getOwnPropertySymbols and Reflect.ownKeys both list symbol keys, so any code holding the object can find the symbol and write through it. Symbols prevent accidental name collisions and keep internal state out of serialized output. They do not stop deliberate access.
Closures: True Privacy Through Scope
A closure is a function that keeps access to the variables of the scope where it was created. If a variable lives only inside a function scope, nothing outside that scope can name it. Privacy through closures has always been genuine.
The Factory Function Pattern
function createCounter() {
let count = 0; // visible only to the functions below
return {
increment() {
count++;
return count;
},
get value() {
return count;
}
};
}
const a = createCounter();
a.increment();
a.increment();
console.log(a.value); // 2
console.log(a.count); // undefined
console.log(Object.keys(a)); // [ 'increment', 'value' ]
a.value = 99; // no setter; ignored in sloppy mode
console.log(a.value); // 2count is not a property at all. It is a local variable, so reflection, serialization, and Object.getOwnPropertySymbols can't find it.
Closures Inside a Class Constructor
You can use the same idea in a class by creating the methods inside the constructor:
class Account {
constructor(initial) {
let balance = initial;
this.deposit = (amount) => {
balance += amount;
};
Object.defineProperty(this, 'balance', {
get: () => balance,
enumerable: true
});
}
}
const x = new Account(5);
const y = new Account(5);
x.deposit(10);
console.log(x.balance); // 15
console.log(y.balance); // 5
console.log(x.deposit === y.deposit); // false: one function per instanceThis version shows what closures cost:
- Memory per instance. Each object gets its own
depositfunction and its own getter. A prototype method is shared by every instance. These are not. - No cross-instance access. A method on
xcannot ready'sbalancevariable. Something likex.equals(y)orx.transferTo(y)has to use the public interface. - No subclass access. A subclass constructor runs after
super()returns, and by then thebalancevariable is out of its reach. - Own properties, not prototype members.
depositandbalancesit on each instance, so a subclass can't override them with a method declared in its class body. The instance property shadows the prototype method.
WeakMaps: Private State Keyed by Instance
A WeakMap is a collection whose keys must be objects and are held weakly. When nothing else references a key object, the garbage collector can reclaim it, and the WeakMap entry goes with it. Put a WeakMap in module scope, key it by instance, and only code inside that module can reach the stored state.
const balances = new WeakMap();
class Account {
constructor(initial) {
balances.set(this, initial);
}
get balance() {
return balances.get(this);
}
deposit(amount) {
balances.set(this, balances.get(this) + amount);
}
transferTo(other, amount) {
if (!balances.has(other)) {
throw new TypeError('Target is not an Account');
}
balances.set(this, balances.get(this) - amount);
balances.set(other, balances.get(other) + amount);
}
}
const a = new Account(100);
const b = new Account(0);
a.transferTo(b, 30);
console.log(a.balance, b.balance); // 70 30
console.log(Object.keys(a)); // []
console.log(JSON.stringify(a)); // '{}'
try {
a.transferTo({}, 10);
} catch (err) {
console.log(err.message); // 'Target is not an Account'
}WeakMaps fix the problems closures have. Methods live on the prototype and are shared. One instance can read another's state, which transferTo relies on. balances.has(other) is a brand check that works the same way as #field in obj.
Why Weak Matters
If you used a regular Map, every instance would stay in memory for as long as the map existed, even after the rest of the program had dropped it. A WeakMap does not keep its keys alive. When an Account becomes unreachable, its entry can be collected. This also explains why a WeakMap can't be iterated and has no size: the engine can remove its contents at any time.
What WeakMaps Still Get Wrong
- Module-level privacy, not class-level privacy. Any function in the same module can read
balances. That is usually fine, but it is a wider boundary than a class body. - Boilerplate. Every read is
balances.get(this). Classes with several private values need several WeakMaps or one WeakMap holding an object. - Silent failure on the wrong receiver. If
thisis not a registered instance,balances.get(this)returnsundefinedand does not throw. A Proxy around anAccountgives youundefinedbalances andNaNarithmetic. A#field throws aTypeErrorin the same situation, which is louder and easier to debug.
WeakMaps also have one ability private fields lack: you can attach hidden data to objects you didn't create, including frozen objects, DOM nodes, or objects from another library. A # field can only be added by the class's own constructor.
Comparing the Approaches
| Concern | Underscore | Symbol key | Closure | WeakMap | `#` field |
|---|---|---|---|---|---|
| Hidden from outside code | No | No (reflection finds it) | Yes | Yes, outside the module | Yes, outside the class body |
| In `Object.keys` / JSON | Yes | No | No | No | No |
| Methods shared on prototype | Yes | Yes | No | Yes | Yes |
| Access to another instance's state | Yes | Yes | No | Yes | Yes |
| Subclass access | Yes | Yes | No | Only in the same module | No |
| Wrong receiver behavior | Reads `undefined` | Reads `undefined` | Unaffected | Returns `undefined` | Throws `TypeError` |
| Attach to objects you didn't create | Yes | Yes | No | Yes | No |
| Minimum version | Any | ES2015 | Any | ES2015 | ES2022 |
Choosing Today
For new class-based code, # fields are usually the right choice. They give class-scoped privacy, shared methods, cross-instance access, and loud errors when misused. Reach for the older patterns when you need one of their specific abilities. Also note that transpilers such as Babel and TypeScript compile # fields to WeakMaps when targeting older engines, so the WeakMap pattern is often what runs in production even when your source code uses #.
Exercise
A codebase uses this._token with a getter token that validates on assignment. A bug report shows invalid tokens reaching the server. Explain the likely cause and name two mechanisms that would prevent it, noting one trade-off of each.
Show answer
Some code writes obj._token = ... directly, which skips the setter's validation, because an underscore enforces nothing. A #token field prevents this at the language level, but subclasses lose access to the state. A module-scoped WeakMap also prevents it and works on older engines, but it adds get/set boilerplate and returns undefined instead of throwing when called on the wrong object.
Exercise
Rewrite createCounter from this chapter as a class whose count is stored in a WeakMap, keeping increment() on the prototype and adding a static method isCounter(obj). What does isCounter use internally?
Show answer
const counts = new WeakMap(); class Counter { constructor() { counts.set(this, 0); } increment() { const n = counts.get(this) + 1; counts.set(this, n); return n; } get value() { return counts.get(this); } static isCounter(obj) { return counts.has(obj); } }. isCounter uses counts.has(obj), the WeakMap version of the #count in obj brand check.
Exercise
Why can't you swap the WeakMap in the Account example for a regular Map without changing behavior?
Show answer
A Map holds strong references to its keys, so every Account ever created stays reachable through the map and is never garbage collected. That is a memory leak. A Map can also be iterated, so any module code could list every instance. A WeakMap allows unreachable instances to be collected and offers no iteration.