0
0
JavascriptConceptBeginner · 3 min read

What is WeakMap in JavaScript: Explanation and Examples

WeakMap in JavaScript is a special kind of object that stores key-value pairs where keys must be objects and are held weakly, meaning they can be removed by garbage collection if no other references exist. This helps manage memory efficiently by automatically cleaning up entries when keys are no longer needed.
⚙️

How It Works

Think of a WeakMap like a locker system where each locker (key) is an object, and inside the locker is some information (value). Unlike regular maps, if the locker itself is lost or thrown away (no other references to the object), the locker and its contents disappear automatically without you needing to clean it up.

This happens because WeakMap holds keys weakly, meaning it does not prevent the JavaScript engine from removing the key object when it is no longer used elsewhere. This helps avoid memory leaks by letting the system free memory for objects that are no longer needed.

However, since keys can disappear anytime, WeakMap does not allow you to list all keys or values, making it different from a regular Map.

💻

Example

This example shows how to create a WeakMap, add an object as a key, and retrieve its value. When the object is no longer referenced, it can be removed automatically.

javascript
const wm = new WeakMap();

let obj = { name: 'Alice' };
wm.set(obj, 'Data for Alice');

console.log(wm.get(obj)); // Output the value

obj = null; // Remove reference to the object

// After this, the entry in WeakMap can be garbage collected automatically
Output
Data for Alice
🎯

When to Use

Use WeakMap when you want to associate data with objects without preventing those objects from being cleaned up by JavaScript's memory management. This is useful in cases like caching, storing metadata, or tracking information about objects without causing memory leaks.

For example, if you build a library that attaches extra info to DOM elements or other objects, WeakMap lets you store that info safely without worrying about manually removing it when the objects are removed.

Key Points

  • Keys must be objects: Primitive values like strings or numbers cannot be keys.
  • Weak references: Keys are held weakly, so they do not prevent garbage collection.
  • No iteration: You cannot list keys or values because entries can disappear anytime.
  • Memory management: Helps avoid memory leaks by cleaning up unused keys automatically.

Key Takeaways

WeakMap keys must be objects and are held weakly to allow automatic garbage collection.
Use WeakMap to attach data to objects without preventing their cleanup and avoid memory leaks.
WeakMap does not support iteration or listing keys because entries can disappear anytime.
It is ideal for caching or storing metadata related to objects safely.