Sub topic 12
Symbols Are Not Private: Comparing Private Fields and WeakMaps
This chapter assumes you already know how to use symbols as property keys and how Object.getOwnPropertySymbols and Reflect.ownKeys list them. You should also be comfortable with ES6 classes, getters, and the idea of an object's identity, meaning that two objects are equal only when they are the same object.
People often treat symbol keys as a way to hide data. They do keep data out of the way, but they do not keep it secret. This chapter shows how symbol-keyed data leaks, then compares the two JavaScript tools that do give real privacy: private class fields and WeakMaps.
What a Symbol Key Hides, and From Whom
A symbol key is skipped by Object.keys, for...in, and JSON.stringify. That protects you from accidents. A loop over an object's keys won't trip over your internal state, and a library that adds a string property called id can't overwrite it.
Code that is actively looking can still find it. Any code that holds the object can list its symbol keys, read them, and change them. Some everyday operations also copy symbol-keyed properties without anyone asking.
const secret = Symbol('secret');
class Account {
constructor(balance) {
this[secret] = balance;
}
get balance() {
return this[secret];
}
}
const acct = new Account(100);
// 1. Reflection finds the key, even without access to the `secret` variable.
const [key] = Object.getOwnPropertySymbols(acct);
acct[key] = 1_000_000;
console.log(acct.balance); // 1000000
// 2. Object spread copies own enumerable symbol properties.
const copy = { ...acct };
console.log(copy[key]); // 1000000
// 3. Object.assign copies them too.
const assigned = Object.assign({}, acct);
console.log(assigned[key]); // 1000000The class never exported secret, yet outside code rewrote the balance in one line. The term for this is soft privacy. Collisions and accidental enumeration can't happen, but deliberate access is easy.
Making the Property Non-Enumerable Doesn't Help Much
You can define the property with enumerable: false. Spread and Object.assign will then skip it, but reflection still lists it.
const secret = Symbol('secret');
const obj = {};
Object.defineProperty(obj, secret, { value: 42, enumerable: false });
console.log({ ...obj }[secret]); // undefined (spread skips it)
console.log(Object.getOwnPropertySymbols(obj)); // [Symbol(secret)]
console.log(Reflect.ownKeys(obj)); // [Symbol(secret)]
console.log(obj[Object.getOwnPropertySymbols(obj)[0]]); // 42Proxies see symbol keys as well. A Proxy's get, set, and ownKeys traps receive them like any other key, so a wrapper around your object can log every symbol access.
Private Class Fields: Hard Privacy Enforced by Syntax
Private class fields, written with a # prefix, give hard privacy. The language itself blocks access from outside the class body. Code outside the class can't even write obj.#field, because that is a SyntaxError at parse time, before the code ever runs.
class Account {
#balance;
constructor(balance) {
this.#balance = balance;
}
get balance() {
return this.#balance;
}
deposit(amount) {
if (amount <= 0) throw new RangeError('Deposit must be positive');
this.#balance += amount;
}
static isAccount(value) {
return #balance in value; // brand check (ES2022)
}
}
const acct = new Account(100);
acct.deposit(50);
console.log(acct.balance); // 150
console.log(Object.getOwnPropertySymbols(acct)); // []
console.log(Reflect.ownKeys(acct)); // []
console.log(JSON.stringify(acct)); // {}
console.log({ ...acct }.balance); // undefined
console.log(Account.isAccount(acct)); // true
console.log(Account.isAccount({})); // falseReflection, spread, JSON, and proxies can't reach a private field. You can't check for one by name from outside either. The #balance in value check is only valid inside the class body, and it returns true only for objects that the class's own constructor initialized. That makes it a dependable brand check: a way to ask "did this class really create this object?" that nobody can fake. A fake object can't pass it by copying properties or setting its prototype.
How Private Fields Work Internally
A private name works like a hidden key that exists only inside the class body's scope. Each object the constructor initializes gets a slot for that name. Code outside the class can't name the field, because the identifier #balance simply doesn't exist there. Code inside the class can read #balance on any instance of the class, not just this. That is why static isAccount works, and why an equals(other) method can compare other.#balance.
Gotcha: Private Fields and Proxies
A private field belongs to the original object, not to a proxy that wraps it. A getter that runs with a proxy as this throws.
class Account {
#balance = 100;
get balance() {
return this.#balance;
}
}
const proxied = new Proxy(new Account(), {});
try {
console.log(proxied.balance);
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message); // engine-specific, e.g. "Cannot read private member..."
}The default get behavior calls the getter with the proxy as the receiver, and the proxy has no #balance slot. Frameworks that wrap state in proxies for reactivity, such as Vue's reactive(), hit this problem. Built-ins like Map behave the same way when proxied, because their internal slots don't pass through a proxy either.
Other Limits
- Private fields exist only in
classsyntax. You can't add one to an object you didn't construct, to a plain object literal, or to a frozen object from a library. - You must declare every private field in the class body. You can't create one dynamically with a computed name.
- Tests and debugging helpers can't reach private state. Browser devtools display private fields, but that's a debugger feature and not something your code can do.
WeakMaps: Privacy Through Scope
A WeakMap stores values keyed by object identity, and it holds those keys weakly: if nothing else references the key object, the garbage collector can reclaim it along with its entry. The privacy comes from scope. If the WeakMap lives in a module and is never exported, no outside code can read it.
const balances = new WeakMap();
class Account {
constructor(balance) {
balances.set(this, balance);
}
get balance() {
return balances.get(this);
}
deposit(amount) {
balances.set(this, balances.get(this) + amount);
}
}
const acct = new Account(100);
acct.deposit(25);
console.log(acct.balance); // 125
console.log(Reflect.ownKeys(acct)); // []
console.log(JSON.stringify(acct)); // {}Before private fields existed, this was the standard way to get hard privacy. It still has a strength that private fields lack: it works on objects you didn't create.
'use strict';
const config = Object.freeze({ env: 'prod' });
const tag = Symbol('loadedAt');
// A symbol key can't be added to a frozen object.
try {
config[tag] = Date.now();
} catch (e) {
console.log(e instanceof TypeError); // true
}
// A WeakMap attaches data without touching the object at all.
const metadata = new WeakMap();
metadata.set(config, { loadedAt: Date.now() });
console.log(typeof metadata.get(config).loadedAt); // "number"This side-table pattern suits DOM nodes, objects returned by third-party code, and caches whose entries should disappear when the key object does.
WeakMap Gotchas
- Lookups go by identity, so a proxy around the object is a different key.
balances.get(new Proxy(acct, {}))returnsundefined. - Every access is a function call and a hash lookup. Engines optimize private fields more directly, so in hot code private fields are usually faster and easier to read.
- The data isn't attached to the object. Spreading or cloning the object leaves the copy with no entry in the map, which may or may not be what you want.
- Whoever holds a reference to the map has full access. Keep it unexported and out of any shared namespace.
Side-by-Side Comparison
| Concern | Symbol key | Private field (`#x`) | WeakMap |
|---|---|---|---|
| Hidden from `Object.keys` / JSON | Yes | Yes | Yes |
| Hidden from `Reflect.ownKeys` | No | Yes | Yes |
| Copied by spread / `Object.assign` | Yes, if enumerable | No | No |
| Readable by outside code | Yes | No | No, if the map isn't exported |
| Works on objects you didn't create | Yes, unless frozen or non-extensible | No | Yes, including frozen objects |
| Works through a Proxy | Yes | No (TypeError) | No (different key) |
| Unforgeable brand check | No | Yes (`#x in obj`) | Yes (`map.has(obj)`) |
| Typical speed | Fast | Fast | Slower per access |
| Main purpose | Avoiding collisions, protocols | Class encapsulation | External side tables |
Choosing Between Them
Use the criteria in this order:
- Is secrecy actually required? If you only want to avoid name clashes or add a hook that cooperating code can use, a symbol is the right tool. Well-known symbols like
Symbol.iteratorwork this way, because the language itself has to find them. - Do you own the constructor? If you do, private fields are the default choice for encapsulation. They are short, fast, and enforced by the parser.
- Will the object be proxied, frozen, or created by someone else? If so, use a
WeakMap.
Exercises
Exercise
A library stores an internal cache on user objects as obj[cacheKey], where cacheKey = Symbol('cache') is never exported. A user reports that after const clone = { ...obj }, changes to the clone's cache show up in the original. Explain why, and name a change that fixes it.
Show answer
Object spread copies own enumerable symbol-keyed properties, so clone[cacheKey] points to the same cache object as obj[cacheKey]. Mutating it through either object affects both. One fix is to keep the cache in a module-level WeakMap keyed by the object, so the cache isn't stored on the object and isn't copied. The clone then gets no entry, or its own entry. Defining the property with enumerable: false would also stop spread from copying it, but reflection could still find it.
Exercise
You turn a class from a symbol-keyed field to #count, and a Vue component that wraps instances in reactive() starts throwing TypeError when it reads a getter. Why does this happen, and which privacy mechanism can you use instead?
Show answer
reactive() returns a Proxy. The getter runs with the proxy as this, and the proxy has no #count slot, so reading this.#count throws a TypeError. A WeakMap keyed by the original instance won't work either, unless you look up the raw object, because the proxy is a different key. Your options are to keep a symbol key, which works through proxies but gives only soft privacy, to call methods on the raw object (for example with Vue's toRaw), or to mark the instance as non-reactive.
Exercise
Write a static method isPoint(value) for a Point class with private fields #x and #y that returns true only for real Point instances, even if someone builds Object.create(Point.prototype).
Show answer
Inside the class body, write static isPoint(value) { return typeof value === 'object' && value !== null && #x in value; }. An object made by Object.create(Point.prototype) passes instanceof Point but was never initialized by Point's constructor, so it has no #x slot, and the check returns false. The null/object guard matters because #x in value throws a TypeError when value is a primitive.