Sub topic 11
Before #: Underscores, Closures, and WeakMaps
This chapter assumes you know ES2015 classes, closures, and the this keyword, and that you have read the earlier chapter on private fields. Private # fields arrived in ES2022. Before that, developers hid state in three main ways. You will still find all three in existing codebases and libraries, so you should be able to read them and know how each one compares to #.
The Underscore Convention
The simplest approach is a naming rule: a leading underscore marks a property as internal.
class Thermostat {
constructor(target) {
this._target = target;
}
get target() {
return this._target;
}
set target(value) {
if (value < 10 || value > 30) throw new RangeError('Out of range');
this._target = value;
}
}
const t = new Thermostat(20);
t._target = 99; // nothing stops this
console.log(t.target); // 99
console.log(Object.keys(t)); // ['_target']The underscore is only a signal to other developers. JavaScript does not enforce it. Any code can read or overwrite _target, which skips the validation in the setter. The property also shows up in Object.keys, for...in, and JSON.stringify. The upside is that the approach costs nothing, works everywhere, and is easy to inspect while debugging.
Closures
A closure gives real privacy. A variable declared inside a function cannot be reached from outside that function. Only the functions created inside it can see the variable.
function createAccount(initial) {
let balance = initial;
return {
deposit(amount) {
if (amount <= 0) throw new RangeError('Deposit must be positive');
balance += amount;
},
get balance() {
return balance;
}
};
}
const acct = createAccount(100);
acct.deposit(50);
console.log(acct.balance); // 150
console.log(Object.keys(acct)); // ['deposit', 'balance']
console.log(acct.secret); // undefined: no path to the variableYou can do the same thing inside a class constructor by declaring methods there instead of on the prototype. Either way, the cost is that every instance gets its own copy of each method. With many instances, that uses more memory than shared prototype methods. Two instances also cannot read each other's private state. With # fields, a method can read other.#balance, which comes in handy for methods like equals.
WeakMaps
A WeakMap stores values keyed by objects. Its keys are held weakly, so an entry is removed once nothing else references the key object. If you declare the map at module scope and do not export it, it acts as a private side table for each instance.
const secrets = new WeakMap();
class Wallet {
constructor(amount) {
secrets.set(this, amount);
}
get amount() {
return secrets.get(this);
}
add(n) {
secrets.set(this, secrets.get(this) + n);
}
}
const w = new Wallet(10);
w.add(5);
console.log(w.amount); // 15
console.log(Object.keys(w)); // []
console.log(JSON.stringify(w)); // '{}'Methods stay on the prototype and are shared, and the state is hidden. When w is garbage collected, its entry in secrets goes with it. A regular Map would keep every wallet alive forever and leak memory.
The privacy only reaches as far as the module. Any code in the same file can call secrets.get(anyWallet). Calling secrets.get({}) on an object that is not a wallet returns undefined without throwing, so bugs can go unnoticed where a # field would throw a TypeError. The code is also more verbose and harder to inspect in devtools.
Comparing the Approaches
| Approach | Enforced privacy | Shared methods | Throws on wrong object | Hidden from JSON/keys |
|---|---|---|---|---|
| Underscore | No | Yes | No | No |
| Closure | Yes | No | Not applicable | Yes |
| WeakMap | Module-scoped | Yes | No (returns `undefined`) | Yes |
| `#` field | Class-scoped | Yes | Yes (`TypeError`) | Yes |
In new code, use # fields. Reach for the older patterns only when you have to work with legacy code, or when you want state that tools and tests can still reach on purpose, which is a case where an underscore can be the honest choice.
Exercise
A module caches per-instance data with const cache = new Map(); cache.set(this, data) in a constructor. Instances are created and discarded frequently. What problem does this cause, and what single change fixes it?
Show answer
A Map holds strong references to its keys, so every instance stays reachable through cache and is never garbage collected. That is a memory leak. Replace new Map() with new WeakMap() so entries are dropped once nothing else references an instance.
Exercise
Why can a closure-based createAccount not implement equals(other) by comparing private balances, while a class using #balance can?
Show answer
Each closure's balance variable is visible only to the functions created in that same call, so one account's methods cannot see another account's variable. A #balance field is scoped to the class body, so any method of the class can read other.#balance on any instance.