freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #47 of 61

weakmap · weakset · gc-friendly

LambdaVSThe Mutator
Lambda saysWeakMap and WeakSet hold object keys weakly, letting them be garbage-collected.

A WeakMap/WeakSet only holds objects, and holds them weakly: if nothing else references the key, it can be garbage-collected (and removed automatically). That makes them ideal for attaching private data or metadata to objects without causing memory leaks. They're not iterable and have no size.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleAttach private data to an object via a WeakMap.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const meta=new WeakMap(); const obj={}; meta.set(obj,{secret:42});
document.getElementById('o').textContent='private: '+meta.get(obj).secret;</script></body></html>
▶ Open the interactive comic issue
‹ Set · Unique ValuesTypeof Vs Instanceof ›