In JavaScript, a WeakMap is a built-in object that allows us to create a collection of key-value pairs where the keys must be objects, and the references to these keys are held weakly.
Similar to WeakSet, the "weak" reference behaviour of WeakMap means that if there are no other references to a key, it may be automatically garbage collected.
Here's a basic overview of how we can use WeakMap in JavaScript:
// Creating an empty WeakMap let yourWeakMap = new WeakMap(); // Adding key-value pairs to the WeakMap let key1 = { id: 1 }; let key2 = { id: 2 }; yourWeakMap.set(key1, 'Alice'); yourWeakMap.set(key2, 'Bob');
set(key, value): Associates a value with a key in the WeakMap. The key must be an object.
let key3 = { id: 3 }; yourWeakMap.set(key3, 'William');
console.log(yourWeakMap.get(key3)); // 'William'
console.log(yourWeakMap.has(key1)); // true console.log(yourWeakMap.has({ id: 3 })); // false, because it's a different object reference
yourWeakMap.delete(key1);
get(key): Retrieves the value associated with a specific key.
has(key): Returns a boolean indicating whether the WeakMap contains a specific key.
delete(key): Removes the key-value pair associated with the specified key.
The key feature of WeakMap is the "weak" reference behaviour. If there are no other references to a key in a WeakMap, the key and its associated value may be automatically garbage collected.
let weakMap = new WeakMap(); let objA = { name: 'Alice' }; let objB = { name: 'Bob' }; weakMap.set(objA, 'Data associated with Alice'); weakMap.set(objB, 'Data associated with Bob'); console.log(weakMap.has(objA)); // true console.log(weakMap.get(objB)); // 'Data associated with Bob' // Removing objA reference objA = null; // At this point, objA may be garbage collected, and weakMap may no longer have a reference to it
Just like WeakSet, WeakMap is useful in scenarios where you want to associate auxiliary data with objects without preventing those objects from being automatically garbage collected when they are no longer needed.