The WeakMap
is a built-in JavaScript object that provides a collection of key-value pairs where the keys must be objects, and the values can be any data type. It is similar to a Map
but has some distinct characteristics:
Weak references: Unlike a Map
, the keys in a WeakMap
are weakly referenced. This means that if the key object has no other references, it can be garbage collected, allowing memory to be freed.
No iteration and size methods: WeakMap
does not provide methods for iterating over its keys, values, or entries. Additionally, there is no size property or method available.
Limited API: The API of WeakMap
is more restricted compared to Map
. It only supports basic operations such as get
, set
, has
, and delete
.
To create a WeakMap
instance, you can use the following syntax:
const weakMap = new WeakMap();
The WeakMap
object is particularly useful when we need to associate additional data or metadata with objects without interfering with the object’s original structure. Some possible use cases include:
Private data: We can use a WeakMap
to store private data associated with objects. Since the keys are weakly referenced, the private data will be automatically discarded when the associated object is garbage-collected.
Object-centric data: WeakMap
can be used to store auxiliary data specific to individual objects. This can be useful when we want to attach additional information to objects without modifying their structure or introducing memory leaks.
Caching and memoization: WeakMap
can be utilized for caching computed results or memoizing function calls, where the keys are function arguments, and the values are the corresponding results.
The following example demonstrates the usage of WeakMap
:
let dad = { name: "Daddy" };let mom = { name: "Mommy" };const myMap = new Map();const myWeakMap = new WeakMap();myMap.set(dad);myWeakMap.set(mom);dad = null;mom = null;console.log(myMap);console.log(myWeakMap);
Lines 1–2: The variables dad
and mom
are initialized as objects with a name
property.
Lines 4–5: The myMap
variable is declared as a new Map
instance, while myWeakMap
is declared as a new WeakMap
instance.
Line 7: The dad
object is added to the myMap
using the set()
method of Map
. Since Map
uses strong references, the dad
object will be retained in memory even if it goes out of scope in the subsequent lines.
Line 8: The mom
object is added to the myWeakMap
using the set()
method of WeakMap
. As WeakMap
uses weak references, the mom
object may be garbage-collected since there are no other references to it after the mom
variable is set to null
.
Lines 10–11: The dad
and mom
variables are set to null
, meaning they no longer hold references to their respective objects.
Free Resources