WeakMap Use Case: Private Data
What You'll Learn
You'll discover how to use WeakMap to store private instance data in JavaScript classes without causing memory leaks.
The Problem with Regular Maps for Private Data
When you want to hide internal data from users of your class, you might be tempted to use a regular Map. However, this creates a memory leak: even after your object is deleted, the Map still holds a reference to it, preventing garbage collection.
WeakMap as the Solution
WeakMap solves this perfectly. Since it only holds weak references to its keys (which must be objects), when your instance is no longer used anywhere else in your code, the WeakMap entry automatically disappears. This makes it ideal for associating private data with object instances.
How It Works
Create a WeakMap outside your class to store private data. Use the instance itself (this) as the key, and store whatever private values you need:
const privateData = new WeakMap();
class BankAccount {
constructor(initialBalance) {
// Store private balance using instance as key
privateData.set(this, { balance: initialBalance });
}
deposit(amount) {
const data = privateData.get(this);
data.balance += amount;
}
getBalance() {
return privateData.get(this).balance;
}
}
const account = new BankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
console.log(account.balance); // undefined - truly private!
The balance is completely inaccessible from outside the class, yet when account is garbage collected, the WeakMap entry vanishes automatically—no memory leak.
Key Takeaway: Use WeakMap to store private instance data by using the object instance as the key; the data remains hidden and is automatically cleaned up when the instance is garbage collected.