Knowledgize

WeakMap Object

A WeakMap is a collection of key-value pairs where the keys are objects and the values can be arbitrary values. Unlike a Map, a WeakMap holds “weak” references to the keys, which means that if there are no other references to the key object, it can be garbage collected, even if it is still present in the WeakMap.



Key Features


  1. Weak References: Keys are held weakly, allowing them to be garbage collected if there are no other references to the object.
  2. Non-iterable: WeakMap is not iterable, meaning it cannot be used in a for...of loop or spread operator.
  3. Only Object Keys: Keys must be objects, and primitive values cannot be used as keys.


Practical Examples


Example 1: Associating Metadata with Objects


You can use a WeakMap to associate metadata with objects without preventing garbage collection of the objects.

const weakMap = new WeakMap(); function Person(name) { this.name = name; } const person1 = new Person('Alice'); const person2 = new Person('Bob'); weakMap.set(person1, { age: 30 }); weakMap.set(person2, { age: 25 }); console.log(weakMap.get(person1)); // Output: { age: 30 } console.log(weakMap.get(person2)); // Output: { age: 25 } person1 = null; // person1 is eligible for garbage collection


Example 2: Managing Private Data


You can use a WeakMap to store private data for objects, ensuring that the data is not accessible from outside and does not prevent the object from being garbage collected.

const privateData = new WeakMap(); class Car { constructor(make, model) { privateData.set(this, { make, model }); } getMake() { return privateData.get(this).make; } getModel() { return privateData.get(this).model; } } const myCar = new Car('Toyota', 'Corolla'); console.log(myCar.getMake()); // Output: Toyota console.log(myCar.getModel()); // Output: Corolla // The privateData is not directly accessible console.log(privateData.get(myCar)); // Output: { make: 'Toyota', model: 'Corolla' } myCar = null; // myCar is eligible for garbage collection


Example 3: Caching Expensive Computations


You can use a WeakMap to cache the results of expensive computations associated with objects without preventing those objects from being garbage collected.

const cache = new WeakMap(); function computeExpensiveOperation(obj) { if (cache.has(obj)) { return cache.get(obj); } else { const result = /* expensive computation based on obj */; cache.set(obj, result); return result; } } let obj = { data: 'some data' }; let result = computeExpensiveOperation(obj); console.log(result); obj = null; // obj is eligible for garbage collection, and the cache entry is also removed