WeakMap
is a collection of key-value pairs where keys must be objects, and values can be any values. Unlike a regular Map
, it holds weak references to keys, allowing them to be garbage-collected if no other references exist. It is often used to associate private data with objects without causing memory leaks and lacks methods for direct iteration to maintain privacy.
Example: Here, the key1
and key2
objects are used as keys in the WeakMap
. If there are no external references to key1
, it becomes eligible for garbage collection, and the corresponding entry in the WeakMap
will be automatically removed.
// Creating a WeakMap const myWeakMap = new WeakMap();
// Creating key objects const key1 = {}; const key2 = {}; // Associating values with weak references myWeakMap.set(key1, 'Value for key1' );
myWeakMap.set(key2, 'Value for key2' );
// Retrieving values console.log(myWeakMap.get(key1)); console.log(myWeakMap.get(key2)); // At this point, the association // between key1 and its value is weak console.log(myWeakMap.get(key1)); |
Value for key1 Value for key2 Value for key1