Private Fields vs WeakMap Pattern
What you'll learn: How modern private fields (#) compare to the older WeakMap pattern for hiding data in classes, and when each approach makes sense.
The Two Approaches to Privacy
Before private fields were added to JavaScript, developers used WeakMaps to store private data. A WeakMap uses object instances as keys to store values that can't be accessed from outside:
const privateData = new WeakMap();
class OldWay {
constructor(secret) {
privateData.set(this, { secret });
}
revealSecret() {
return privateData.get(this).secret;
}
}
const old = new OldWay('hidden');
// No way to access 'secret' directly
console.log(old.revealSecret()); // 'hidden'
With modern private fields, the same privacy is built into the language:
class ModernWay {
#secret;
constructor(secret) {
this.#secret = secret;
}
revealSecret() {
return this.#secret;
}
}
const modern = new ModernWay('hidden');
console.log(modern.revealSecret()); // 'hidden'
When to Use Each
Use private fields (#) for new code—they're cleaner, faster, and part of the standard. The syntax is clear, and the engine can optimize them better.
Use WeakMaps when you need to add private data to objects you didn't create, or when working in environments that don't support private fields yet. WeakMaps also work outside of classes entirely.
The WeakMap pattern requires managing an external WeakMap for each piece of private data, which is more verbose. Private fields keep everything self-contained within the class definition.
Key Takeaway: Private fields (#) are the modern, cleaner way to achieve privacy in classes, while WeakMaps remain useful for adding private data to external objects or for legacy compatibility.