Sub topic 12
Symbols Are Not Private: Comparing Private Fields and WeakMaps
This chapter assumes you know ES6 classes, computed property names, and the reflection methods from the earlier chapter, Object.getOwnPropertySymbols and Reflect.ownKeys. It shows why a symbol key hides data only from casual inspection. It then compares symbol keys with the two tools that actually make data private: private class fields and WeakMaps.
Why Symbol Keys Feel Private
Symbol-keyed properties don't appear in Object.keys, for...in, or JSON.stringify. If you never export the symbol, other modules can't type obj[mySymbol], because they have no reference to the symbol. That is enough to stop accidental access and name collisions. It does not stop deliberate access.
How Symbol Keys Leak
Any code that holds the object can ask for its symbol keys and then read the values:
const secret = Symbol('secret');
class Account {
#balance = 100;
constructor() {
this[secret] = 'hidden?';
}
}
const acct = new Account();
const [sym] = Object.getOwnPropertySymbols(acct);
console.log(acct[sym]); // "hidden?" (symbol keys can be discovered)
// acct.#balance; // SyntaxError outside the class bodySeveral other routes expose symbol keys too:
Reflect.ownKeys(obj)returns string and symbol keys together.Object.assign({}, obj)and object spread{ ...obj }copy enumerable symbol-keyed properties.- A
Proxywrapped around the object sees every symbol key in itsgetandownKeystraps. - Browser and Node.js developer tools display symbol properties.
The symbol property is also writable by default, so outside code can overwrite the value as well as read it.
Private Class Fields: Real Encapsulation
A private field such as #balance exists only inside the class body. Reflection can't list it, JSON.stringify and spread skip it, and code outside the class can't even name it. Writing acct.#balance outside the class is a syntax error, not a runtime error.
Inside the class, use #field in obj to check whether an object has the field. This is called a brand check:
class Account {
#balance = 0;
deposit(amount) {
this.#balance += amount;
return this.#balance;
}
static isAccount(obj) {
return #balance in obj;
}
}
const a = new Account();
console.log(a.deposit(50)); // 50
console.log(Account.isAccount(a)); // true
console.log(Account.isAccount({})); // false
console.log(Reflect.ownKeys(a)); // []Private fields have limits. You can't add them to objects your class didn't create, and you can't share them with code outside the class body.
WeakMaps: Privacy Outside a Class
A WeakMap keeps the data in a separate table keyed by the object. The object itself carries nothing extra, so reflection finds nothing. Because the map holds its keys weakly, the entry can be garbage-collected once the object is no longer referenced anywhere else.
const balances = new WeakMap();
function openAccount(initial) {
const account = {};
balances.set(account, initial);
return account;
}
function balanceOf(account) {
return balances.get(account);
}
const acct = openAccount(75);
console.log(balanceOf(acct)); // 75
console.log(Reflect.ownKeys(acct)); // []
console.log(JSON.stringify(acct)); // {}Use a WeakMap when you need to attach private data to objects you don't control, such as DOM nodes or objects from a library. It also works when several functions in one module share the data and no class is involved.
Choosing Between Them
| Need | Symbol key | Private field | WeakMap |
|---|---|---|---|
| Avoid name collisions | Yes | Yes | Yes |
| Hidden from `Object.keys` and JSON | Yes | Yes | Yes |
| Hidden from reflection | No | Yes | Yes |
| Works on objects you didn't create | Yes | No | Yes |
| Other code can deliberately use it | Yes, if it has the symbol | No | Only code holding the map |
Symbol keys are the right tool when you want a collision-free extension point that other code can use on purpose, like the well-known symbols. When you need privacy, use a private field or a WeakMap.
Exercise
A library hands you plain objects, and you need to attach a cache to each one that no other code can read, even through reflection. Which approach fits, and why don't the other two?
Show answer
Use a WeakMap keyed by each object. A symbol key would show up in Object.getOwnPropertySymbols and Reflect.ownKeys, so other code could find and read it. Private fields only exist on instances your own class creates, so you can't add them to the library's objects.
Exercise
What does this log? const k = Symbol('k'); const o = { [k]: 1 }; const copy = { ...o }; console.log(copy[k]);
Show answer
It logs 1. Object spread copies enumerable symbol-keyed properties, which is one more way symbol-keyed data leaves the original object.