JS WeakMap and WeakSet
In this page:
const weakMap = new WeakMap();
weakMap.set(objectKey, value);
const weakSet = new WeakSet();
weakSet.add(object);
WeakMap Basics
WeakMap stores key-value pairs where keys must be objects. It does not prevent those keys from being garbage collected.
Because WeakMap keys can still be garbage collected once nothing else references them, WeakMap avoids the memory leaks a regular Map would create if you forgot to clean up entries.
उदाहरण: WeakMap Basics
// Declare the constant `wm` as a new `WeakMap` instance
// Declare the constant `wm` as a new `WeakMap` instance
const wm = new WeakMap();
// Declare the constant `obj`, set to `{}`
// Declare the constant `obj`, set to `{}`
const obj = {};
// Call `wm.set(obj, "some data")`
// Call `wm.set(obj, "some data")`
wm.set(obj, "some data");
// Print `wm.get(obj)` to the console
// Print `wm.get(obj)` to the console
console.log(wm.get(obj));
WeakMap Object Keys
WeakMap keys must be objects. Strings, numbers, and other primitive values cannot be keys.
This restriction is what enables the garbage-collection benefit: primitives are never garbage collected the way object references are, so allowing them as keys wouldn't make sense.
उदाहरण: WeakMap Object Keys
const wm = new WeakMap();
const key = {};
wm.set(key, "value");
// wm.set("string", "value"); // TypeError: Invalid value used as weak map key
console.log(wm.get(key));
WeakSet Basics
WeakSet stores objects. It is useful when you only need to know whether an object has been added.
Unlike a regular Set, a WeakSet doesn't support iteration or a size property, trading those conveniences for the same automatic-cleanup benefit as WeakMap.
उदाहरण: WeakSet Basics
// Declare the constant `ws` as a new `WeakSet` instance
// Declare the constant `ws` as a new `WeakSet` instance
const ws = new WeakSet();
// Declare the constant `obj`, set to `{}`
// Declare the constant `obj`, set to `{}`
const obj = {};
// Call `ws.add(obj)`
// Call `ws.add(obj)`
ws.add(obj);
// Print `ws.has(obj)` to the console
// Print `ws.has(obj)` to the console
console.log(ws.has(obj));
WeakMap and Private Data
A WeakMap can keep data associated with objects without adding visible properties to those objects.
This is a common pattern for simulating private class fields before native private fields existed, since outside code has no way to enumerate or access the WeakMap directly.
उदाहरण: WeakMap and Private Data
// Declare the constant `privateData` as a new `WeakMap` instance
// Declare the constant `privateData` as a new `WeakMap` instance
const privateData = new WeakMap();
// Define the class `User`
// Define the class `User`
class User {
// Constructor taking `name`, runs when a new instance is created
// Constructor taking `name`, runs when a new instance is created
constructor(name) {
// Call `privateData.set(this, { name })`
// Call `privateData.set(this, { name })`
privateData.set(this, { name });
}
// Define the method `getName` with no parameters
// Define the method `getName` with no parameters
getName() {
// Return `privateData.get(this).name` from this function
// Return `privateData.get(this).name` from this function
return privateData.get(this).name;
}
}
// Print `new User("Sam").getName()` to the console
// Print `new User("Sam").getName()` to the console
console.log(new User("Sam").getName());
When to Use Weak Collections
Use WeakMap or WeakSet when object lifetime matters and you do not need normal iteration over the collection.
Reach for WeakMap/WeakSet when you're associating metadata with objects you don't own the lifetime of, and for plain Map/Set otherwise, since they support far more operations.
उदाहरण: When to Use Weak Collections
// Declare the constant `visited` as a new `WeakSet` instance
// Declare the constant `visited` as a new `WeakSet` instance
const visited = new WeakSet();
// Define the function `markVisited` taking `node`
// Define the function `markVisited` taking `node`
function markVisited(node) { visited.add(node); }
// Declare the constant `el`, set to `{}`
// Declare the constant `el`, set to `{}`
const el = {};
// Call `markVisited(el)`
// Call `markVisited(el)`
markVisited(el);
// Print `visited.has(el)` to the console
// Print `visited.has(el)` to the console
console.log(visited.has(el));
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: