Understanding WeakMap and WeakSet in JavaScript

Day 19 of me reading random and basic but important coding facts...... Today I learnt about a very underrated topic: WeakMap and WeakSet. We all use Map everywhere, but few know that Map has a problem. In a Map, keys are strongly held. This means if we use an object as a key like map.set(obj, "data")......that object now exists in memory. Even if we set obj = null everywhere else in the code, the object still exists in memory as long as the Map exists. The garbage collector cannot touch it because the Map is still holding it. This leads to memory leaks. The solution is simple: WeakMap & WeakSet. These structures hold weak references to their keys (objects only). If the key object is deleted or becomes unreachable elsewhere in your code, WeakMap automatically releases it. The entry is removed from the map, and the memory gets freed. We use WeakMap for: 1. Caching/Memoization: To store the result of a heavy calculation on an object. e.g., cache.set(obj, result) If obj is later deleted by the app, the cached result is automatically wiped from memory. 2. DOM Node Tracking: Associating data with a DOM element. When the element is removed from the DOM, the data vanishes. It is a very, very important use case. Vue.js uses it to track reactivity without leaks, and Angular uses it to link metadata to components. It is the industry standard for associating data with objects you don't own. But if WeakMap is so good, why do we use Map? Why not always use WeakMap? The answer is: in Map, keys can be primitives as well as objects, but WeakMap can only have objects as keys. Also, we can iterate over Map, but we can't in WeakMap. So, the rule of thumb is: Use Map when you need a resilient data store that you need to count or iterate over. Use WeakMap when you are adding secondary data to objects that have a lifecycle managed by something else. Keep Learning!!!!!!! #JavaScript #WebDevelopment #Coding #MemoryManagement #SoftwareEngineering #FrontendDev

  • diagram

To view or add a comment, sign in

Explore content categories