JavaScript WeakMap
The WeakMap
object is a collection of key/value pairs in which the keys must be objects and the values can be arbitrary values. The difference between a WeakMap
and a Map
is that a WeakMap
allows its keys to be garbage collected, while a Map
does not.
Syntax
new WeakMap([iterable])
iterable
: An iterable object whose elements are key/value pairs (e.g. arrays), or an object whose own enumerable properties will be used as the key/value pairs.
Example
const wm = new WeakMap();
let o1 = {};
let o2 = {};
wm.set(o1, "foo");
wm.set(o2, "bar");
console.log(wm.get(o1)); // output: "foo"
console.log(wm.get(o2)); // output: "bar"
wm.delete(o2);
console.log(wm.get(o2)); // output: undefined
Output
foo
bar
undefined
Explanation
In the above example, we create a new WeakMap
object wm
. We then create two different objects, o1
and o2
. We add key/value pairs to wm
using set()
method, where o1
is the key for "foo"
and o2
is the key for "bar"
. We retrieve the values using get()
method.
We then delete the key/value pair where o2
is the key using delete()
method. We try to retrieve the value again using get()
method but it returns undefined because o2
has been deleted.
Use
WeakMap
is useful when you need to associate some data with an object but you don't want to create a strong reference to it. This can help prevent memory leaks in your application.
Important Points
- Keys must be objects and values can be arbitrary values.
- Allows keys to be garbage collected.
- Not iterable.
Summary
WeakMap
is a special type of map that allows its keys to be garbage collected. It is useful in situations where you want to associate some data with an object, but don't want to create a strong reference to it.