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
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?