Suggest an editImprove this articleRefine the answer for “WeakMap VS Map”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)The difference between **`Map`** and **`WeakMap`** in JavaScript is fundamental: both store «key -> value» pairs, but `WeakMap` was created for special cases where you need to attach data to objects without interfering with the garbage collector (GC). **Key point:** `WeakMap` keys can only be objects and are held by weak references, so the GC can automatically remove the object and its entry.Shown above the full answer for quick recall.Answer (EN)ImageThe difference between `Map` and `WeakMap` in JavaScript is fundamental. Both store **"key -> value"** pairs, but `WeakMap` was created for **special cases** where you need to **"attach data to objects" without interfering with the garbage collector (GC)**. --- ## The main idea: | Property | `Map` | `WeakMap` | |---|---|---| | Keys | any values (strings, numbers, objects) | **objects only** | | Reference type | strong (the object stays alive while a reference exists) | **weak** (the GC can remove the object) | | Iteration (`for...of`, `.keys()`, `.size`) | yes | no | | Checking the size | `.size` | no | | Usage | general-purpose key-value pairs | temporary "attachments" to objects | --- ## Example with `Map`: ```javascript const map = new Map(); let user = { name: "Alice" }; map.set(user, "User"); console.log(map.get(user)); // "User" user = null; // remove the reference console.log(map); // Map still holds { name: "Alice" } ``` The object won't be removed from memory as long as `Map` holds a reference to it, which is a **memory leak**. --- ## Now `WeakMap`: ```javascript const weakMap = new WeakMap(); let user = { name: "Alice" }; weakMap.set(user, "User"); console.log(weakMap.has(user)); // true user = null; // the object becomes unreachable // the object will be automatically removed by the garbage collector! ``` - If an object is no longer **reachable** from the code, the garbage collector removes both the object itself and its entry in `WeakMap`. - `WeakMap` does not prevent memory cleanup. --- ## What does a "weak reference" mean? A "weak" reference is a reference that **does not prevent the garbage collector from removing an object** if there are no other "strong" references to it. In a regular `Map`, keys are held "strongly": as long as the `Map` exists, all its keys and values stay in memory. In `WeakMap` they don't: the GC can clear them at any moment. --- ## WeakMap methods: | Method | Description | |---|---| | `set(key, value)` | add a value for an object | | `get(key)` | retrieve a value | | `has(key)` | check whether an entry exists | | `delete(key)` | remove an entry | **Missing:** `size`, `keys()`, `values()`, `entries()`, `forEach()` - because `WeakMap` is **not iterable**. --- ## Example of practical usage: Storing **private data for objects** ```javascript const privateData = new WeakMap(); class User { constructor(name, age) { privateData.set(this, { age }); this.name = name; } getAge() { return privateData.get(this).age; } } const alice = new User("Alice", 30); console.log(alice.getAge()); // 30 // After alice is removed, the object and its private data disappear from memory ``` - The private data isn't visible from the outside, - it gets cleaned up automatically when the object is removed. --- ## Another example: caching ```javascript const cache = new WeakMap(); function getData(obj) { if (!cache.has(obj)) { const data = Math.random(); // suppose this is expensive to compute cache.set(obj, data); } return cache.get(obj); } let user = {}; console.log(getData(user)); // the cache entry is created user = null; // the object and its cache entry are automatically cleared ``` Ideal for temporarily storing computed data without memory leaks. --- ## In short: | Property | `Map` | `WeakMap` | |---|---|---| | Key type | any | objects only | | Iterating elements | yes | no | | Relationship to objects | strong | weak | | Automatic removal | no | yes | | Usage | cache, dictionaries, configs | private data, leak-free cache |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.