JavaScript - WeakMap

A WeakMap is a set of key-value pairs in which the keys are objects and the values can be any data type. In contrast to a conventional Map, the keys in a WeakMap are held "weakly," which means they do not impede garbage collection if the key object is no longer referenced elsewhere in the application. This makes WeakMap especially handy when you need to associate data with an object but don't want it to get garbage collected.

One of the primary advantages of WeakMap is its ability to prevent memory leaks when objects are transient or should be cleaned up after they are no longer required.  For example, WeakMap is frequently used to store private data connected with objects, especially in cases where the object lifetime is dynamic or complex.

Here’s a simple example of using WeakMap:

let weak_Map = new WeakMap();

let obj = {};

weak_Map.set(obj, 'Important Data');

console.log(weak_Map.get(obj)); // Outputs: 'Important Data'

obj = null; // The object is dereferenced and will be garbage-collected

In this example, once the object obj is set to null, the reference in the WeakMap is automatically cleared by the garbage collector, ensuring efficient memory usage.