WeakMap for Private Data
You'll learn how to store truly private instance data outside the object itself using a WeakMap keyed by object reference.
The Problem with Other Privacy Methods
Closures give you privacy but can make code harder to scale across multiple methods. The underscore convention (_property) is just a social contract—nothing stops external code from accessing those properties. You need a way to keep data completely separate from the object.
How WeakMap Achieves Privacy
A WeakMap is a special collection where keys must be objects. You can store private data outside your object, keyed by the object itself. External code can't access the WeakMap unless they have a reference to it (which you keep private), and the data doesn't appear on the object at all.
const privateData = new WeakMap();
class BankAccount {
constructor(balance) {
privateData.set(this, { balance });
}
deposit(amount) {
const data = privateData.get(this);
data.balance += amount;
}
getBalance() {
const data = privateData.get(this);
return data.balance;
}
}
const account = new BankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
console.log(account.balance); // undefined
console.log(Object.keys(account)); // []
The balance is completely invisible from outside. No property exists on account itself—the data lives in the privateData WeakMap, retrievable only by those who have that WeakMap reference.
Why "Weak"?
When the object is garbage collected, its entry in the WeakMap automatically disappears. You don't leak memory by holding private data for objects that no longer exist.
Key Takeaway: WeakMaps let you store private instance data by using the object as a key in an external map that only your class methods can access, achieving true encapsulation without polluting the object's own properties.