# WeakMap and WeakSet

> What are WeakMap and WeakSet in JavaScript, and how do they differ from Map and Set in terms of keys, iteration and garbage collection?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-weakmap-weakset
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What are WeakMap and WeakSet in JavaScript, and how do they differ from Map and Set in terms of keys, iteration and garbage collection?

## Answer

`WeakMap` is a key-value collection whose keys must be objects (or non-registered symbols since ES2023), and it holds those keys weakly: if nothing else in the program references a key, the garbage collector can reclaim it and the entry disappears. `WeakSet` is the same idea for a set of objects. Because entries can vanish at any time, neither collection is iterable and neither has a `size`, which is the main practical difference from `Map` and `Set`.

### What "held weakly" actually means

A normal `Map` keeps a strong reference to every key. If you use a DOM node as a key and later remove the node from the page, the `Map` still keeps it alive, so the node and everything it points to leaks until you call `delete`.

A `WeakMap` does not count as a reference for garbage collection purposes. Once the last strong reference to the key object is gone, the key, and the value associated with it, become eligible for collection. The value is held strongly only as long as the key is alive. This structure is called an ephemeron.

### Map vs WeakMap and Set vs WeakSet

| Feature | Map / Set | WeakMap / WeakSet |
| --- | --- | --- |
| Key types | Any value, including primitives | Objects and non-registered symbols only |
| Reference to key | Strong | Weak |
| Iteration (`for...of`, `keys()`, `forEach`) | Yes | No |
| `size` and `clear()` | Yes | No |
| Methods | `get`, `set`, `has`, `delete`, and more | `get`, `set`, `has`, `delete` (WeakSet: `add`, `has`, `delete`) |
| Typical use | General lookup tables, caches you control | Metadata attached to objects you do not own |

The lack of iteration is deliberate. If you could list the keys, the result would depend on when the garbage collector last ran, which would make programs non-deterministic.

### Where they are used in real code

- **Private data per instance**: before `#private` fields existed, libraries stored private state in a module-level `WeakMap` keyed by `this`. Babel and TypeScript still compile `#private` fields to WeakMaps when targeting older runtimes.
- **Caching results for objects**: memoise an expensive computation per object (for example a parsed config object) without keeping the object alive forever.
- **DOM metadata**: attach state to elements you did not create, such as a tooltip instance per button, and let it go when the element is removed.
- **Visited tracking**: a `WeakSet` of objects already processed, for detecting cycles in a deep clone or deep equality check.
- **Branding**: a `WeakSet` of instances created by your factory lets you check "was this created by me?" without adding a visible property.

### Common mistakes

- Trying to use a string or number as a key throws `TypeError: Invalid value used as weak map key`.
- Expecting entries to disappear immediately. Collection is non-deterministic; you cannot observe it and should not write logic that depends on timing.
- Using `WeakMap` when you need to list or count entries. If you need iteration, you need a `Map` plus explicit cleanup.
- Confusing `WeakMap` with `WeakRef`. `WeakRef` (ES2021) is a weak reference to a single object that you can `deref()`, and `FinalizationRegistry` lets you run a callback after collection. Both are lower level and the spec authors advise avoiding them unless you really need them.

**Map vs WeakMap during garbage collection. Switch the holder between Map and WeakMap under Tweak and run the collector.**

1. **Roots**: The collector starts from variables in scope, globals and active timers.
2. **Map keys are strong**: A Map entry keeps its key object alive: a leak if never deleted.
3. **WeakMap keys are weak**: They don't count for reachability, so the object is collected.
4. **Entry disappears**: When the key object is collected, its WeakMap entry goes with it.

## Code examples

### Private per-instance state with WeakMap

```
const privateState = new WeakMap();

class Wallet {
  constructor(ownerId) {
    privateState.set(this, { ownerId, balanceInPaise: 0 });
  }
  deposit(paise) {
    privateState.get(this).balanceInPaise += paise;
  }
  get balance() {
    return privateState.get(this).balanceInPaise / 100;
  }
}

const w = new Wallet('user_42');
w.deposit(25050);
console.log(w.balance);
console.log(Object.keys(w));
// When `w` becomes unreachable, its WeakMap entry can be collected too.
```

The state is invisible on the instance and is tied to the instance's lifetime. This is the pattern compilers use to downlevel #private fields.

### Weak tracking for a cycle-safe deep clone

```
function deepClone(value, seen = new WeakMap()) {
  if (value === null || typeof value !== 'object') return value;
  if (seen.has(value)) return seen.get(value); // cycle: reuse clone

  const copy = Array.isArray(value) ? [] : {};
  seen.set(value, copy);
  for (const key of Object.keys(value)) {
    copy[key] = deepClone(value[key], seen);
  }
  return copy;
}

const user = { name: 'Asha' };
user.self = user; // circular reference

const clone = deepClone(user);
console.log(clone.self === clone);
console.log(clone === user);
```

A WeakMap remembers which objects have already been cloned, so circular references map to the same copy instead of recursing forever. When the clone call finishes, the tracking map holds nothing alive.

## Key points

- WeakMap and WeakSet keys must be objects (or non-registered symbols since ES2023), never primitives.
- Keys are held weakly; when the key is unreachable elsewhere, the entry can be garbage collected.
- No iteration, no size, no clear, because the contents depend on GC timing.
- Ideal for attaching metadata or caches to objects you do not own.
- WeakRef and FinalizationRegistry are different, lower-level APIs for single weak references.

## Common follow-up questions

- Why can you not iterate over a WeakMap?
- How would you implement a memoize function that caches by object argument without leaking memory?
- What is the difference between WeakMap and WeakRef?
- How do compilers transpile #private class fields for older targets?

## Interview tips

- Lead with the one-line difference: weak keys mean the entry does not keep the object alive, so no iteration or size.
- Give a concrete leak scenario with a Map and DOM nodes, then show how a WeakMap fixes it.
- Do not claim entries are removed immediately; say they become eligible for collection.

## Concepts covered

WeakMap, WeakSet, Garbage Collection, Weak References, Memory Management

Previous: [Proxy and Reflect API](https://www.internhack.in/learn/interview/javascript-interview/js-proxy-reflect) · Next: [Generator Functions](https://www.internhack.in/learn/interview/javascript-interview/js-generators) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Optional Chaining and Nullish Coalescing](https://www.internhack.in/learn/interview/javascript-interview/js-optional-chaining-nullish)
- [Currying and Function Composition](https://www.internhack.in/learn/interview/javascript-interview/js-currying-composition)
- [Memoization](https://www.internhack.in/learn/interview/javascript-interview/js-memoization)
- [Property Descriptors and Object.defineProperty](https://www.internhack.in/learn/interview/javascript-interview/js-property-descriptors)
- [Deep Cloning: structuredClone vs JSON](https://www.internhack.in/learn/interview/javascript-interview/js-structuredclone)
- [JavaScript Design Patterns](https://www.internhack.in/learn/interview/javascript-interview/js-design-patterns)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
