WeakMap in JavaScript (Live Playground)
The WeakMap
data structure is an advanced JavaScript feature that holds key-value pairs with weakly referenced keys. It is similar to a regular Map
, but its keys are not enumerable and will not prevent garbage collection. In this tutorial, we will explore how to work with WeakMap
and its methods.
Creating a WeakMap
To create a WeakMap, use the WeakMap
constructor. You can create an empty WeakMap or initialize it with an iterable of key-value pairs:
const emptyWeakMap = new WeakMap();
const keyValuePairs = [
[{ id: 1 }, 'First value'],
[{ id: 2 }, 'Second value'],
[{ id: 3 }, 'Third value'],
];
const initializedWeakMap = new WeakMap(keyValuePairs);
Note that only objects can be used as keys in a WeakMap
. Primitive values like numbers or strings will throw a TypeError.
Adding Key-Value Pairs
To add a key-value pair to a WeakMap
, use the set
method:
const myWeakMap = new WeakMap();
const key1 = { id: 1 };
const value1 = 'First value';
const key2 = { id: 2 };
const value2 = 'Second value';
myWeakMap.set(key1, value1);
myWeakMap.set(key2, value2);
Getting Values
To retrieve the value associated with a key in a WeakMap
, use the get
method:
const value = myWeakMap.get(key1); // Returns 'First value'
Removing Key-Value Pairs
To remove a key-value pair from a WeakMap
, use the delete
method:
myWeakMap.delete(key1); // Removes the key-value pair with key1 from the WeakMap
Checking for Key-Value Pairs
To check if a WeakMap
contains a specific key, use the has
method:
myWeakMap.has(key1); // Returns true if the key is in the WeakMap, otherwise false
Limitations of WeakMaps
WeakMaps do not provide a method to iterate over their key-value pairs, nor do they have a size
property. This is because their keys are weakly referenced, which allows them to be garbage collected when they are no longer accessible.
Conclusion
In this tutorial, we have learned about the WeakMap
data structure in JavaScript, which is designed to hold key-value pairs with weakly referenced keys. We've learned how to create a WeakMap, add key-value pairs, retrieve values, remove key-value pairs, and check for keys in the map. WeakMaps can be useful when you need to store key-value pairs without preventing their keys from being garbage collected.