capypad
0 day streak
javascript / intermediate
Snippet

Managing Private State with WeakMap

WeakMap is a collection of key/value pairs in which the keys are objects and are weakly referenced. This is an intermediate pattern for creating truly private state in JavaScript classes before the native '#' syntax was widely adopted, and it ensures that private data is garbage collected when the instance is destroyed.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const privateData = new WeakMap();
 
class SecureUser {
constructor(name, token) {
privateData.set(this, { name, token });
}
 
getProfile() {
const { name } = privateData.get(this);
return `User: ${name}`;
}
}
 
const user = new SecureUser('Alice', 'secret-123');
console.log(user.token); // undefined
Breakdown
1
const privateData = new WeakMap();
Creates a map where keys (objects) do not prevent garbage collection.
2
privateData.set(this, { name, token });
Stores sensitive data associated with the current instance ('this') outside the object itself.
3
privateData.get(this);
Retrieves the stored private data using the current instance as the lookup key.