JavaScript Course
JavaScript
/
Advanced

WeakMap & WeakSet

Definition

WeakMap is a collection of key/value pairs in which the keys must be objects, and those keys are held 'weakly'—meaning if there are no other references to the key object, the Garbage Collector will delete the key/value pair from the WeakMap.

Explain Like I'm New

Normal Maps keep objects alive forever. If you put a DOM element in a Map, and then remove the element from the screen, it stays in the computer's memory forever (Memory Leak). A WeakMap is a self-cleaning Map. If the DOM element is removed from the screen, the WeakMap realizes it's useless and throws it in the trash automatically.

Real World Example

Vue 3's Reactivity system uses WeakMaps heavily. When a component is destroyed, the WeakMap automatically cleans up the reactivity watchers associated with that component's data objects.

Common Use Cases

  • •Caching data attached to DOM nodes
  • •Private class variables

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What is the main difference between a Map and a WeakMap?

intermediate

  • Why can't you iterate (`for...of`) over a WeakMap?

advanced

  • Can you use a string as a key in a WeakMap?

Flash Cards

Question

Why can't you iterate over a WeakMap?

Click to reveal answer
Answer

Because the Garbage Collector operates unpredictably. You never know exactly WHEN it will delete an unreferenced object. If you could iterate over a WeakMap, the length would randomly change based on when the GC decides to run, causing chaotic bugs.

Question

Can you use a string as a key?

Click to reveal answer
Answer

No. Keys in a WeakMap MUST be Objects or Symbols. Primitive values like strings or numbers cannot be garbage collected in the same way objects can, so they violate the entire purpose of a WeakMap.