Computer >> Computer tutorials >  >> Programming >> Javascript

Why do we need weakMaps in Javascript?


The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values.

According to wikipedia, Weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. An object referenced only by weak references – meaning "every chain of references that reaches the object includes at least one weak reference as a link" – is considered weakly reachable, and can be treated as unreachable and so may be collected at any time.

Some use cases that would otherwise cause a memory leak which can be worked around using weak maps −

  • Keeping private data about a specific object and only giving access to it to people with a reference to the Map.

  • Keeping data about library objects without changing them or incurring overhead.

  • Keeping data about a small set of objects where many objects of the type exist to not incur problems with hidden classes JS engines use for objects of the same type.

  • Keeping data about host objects like DOM nodes in the browser.

  • Adding a capability to an object from the outside.