What is the WeakMap object in JavaScript?
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 aWeakMapare 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:
WeakMapdoes 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
WeakMapis more restricted compared toMap. It only supports basic operations such asget,set,has, anddelete.
Syntax
To create a WeakMap instance, you can use the following syntax:
const weakMap = new WeakMap();
Possible usage
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
WeakMapto 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:
WeakMapcan 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:
WeakMapcan be utilized for caching computed results or memoizing function calls, where the keys are function arguments, and the values are the corresponding results.
Code example
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);
Code explanation
-
Lines 1–2: The variables
dadandmomare initialized as objects with anameproperty. -
Lines 4–5: The
myMapvariable is declared as anew Mapinstance, whilemyWeakMapis declared as anew WeakMapinstance. -
Line 7: The
dadobject is added to themyMapusing theset()method ofMap. SinceMapuses strong references, thedadobject will be retained in memory even if it goes out of scope in the subsequent lines. -
Line 8: The
momobject is added to themyWeakMapusing theset()method ofWeakMap. AsWeakMapuses weak references, themomobject may be garbage-collected since there are no other references to it after themomvariable is set tonull. -
Lines 10–11: The
dadandmomvariables are set tonull, meaning they no longer hold references to their respective objects.
Free Resources