New Built-in Classes: WeakSet and WeakMap
Get to know about the roles of WeakMap and WeakSet in JavaScript in detail.
WeakSet
and WeakMap
Suppose you added an object as a value to a Set
or as a key to a Map
. If that object is no longer needed in your application, it can’t be garbage collected. The Set
or the Map
that holds on to the object will prevent it from being cleaned up. This is not very gentle on memory usage and may be an issue in some applications that use a large amount of data. WeakSet
, a counterpart of Set
, and WeakMap
, a counterpart of Map
, can be used to solve this issue since both have a minimal impact on memory usage.
The word weak
refers to coupling, as in weak coupling. A Set
, for example, tightly holds onto the data that is added. However, a WeakSet
will hold only weakly and will not prevent the object from being released. Let’s discuss why we may need a weak collection before looking at the built-in weak collections in JavaScript.
An analogy
Suppose you have an application where information about various vehicles based on vehicle identification number (VIN) is obtained from a database.
Get hands-on with 1200+ tech skills courses.