Tutorials JavaScript WeakMap & WeakSet
Ch 56 / 78
Advertisement
📢 Ad space · 728 × 90 · Replace slot ID above
Chapter 56 Advanced 6 min read JavaScript

WeakMap & WeakSet

JavaScript's regular Map and Set keep their keys and values alive forever — even after every other reference to those objects is gone. WeakMap and WeakSet solve this by holding only weak references to their object keys — allowing the garbage collector to reclaim memory the moment those objects are no longer needed elsewhere. They are the go-to tool for storing metadata about objects without leaking memory.

What you'll learn
What a weak reference is and why it matters for memory
WeakMap API — set, get, has, delete
WeakSet API — add, has, delete
Why WeakMap & WeakSet are not iterable
WeakMap vs Map — when to choose which
Real patterns — private data, caching, visited tracking

Three Things to Know Before You Start

WeakMap and WeakSet are specialised versions of Map and Set. Before diving into the API, understand the three foundational ideas that explain every design decision:

WeakMap
Key → Value, Object Keys Only
A collection of key/value pairs where keys must be objects (or registered Symbols). Holds a weak reference to each key — when the key object has no other references, the entry is garbage-collected automatically.
API: set, get, has, delete — that's it. No size, no iteration.
WeakSet
Object-Only Set
A collection of unique objects (no primitives). Holds a weak reference to each item — when an object has no other references it is removed from the set automatically. Great for tagging objects.
API: add, has, delete — no size, no iteration.
Weak Reference
GC-Friendly Hold
A weak reference does not prevent the garbage collector from reclaiming an object. Once the only remaining reference to an object is a WeakMap key or WeakSet entry, that object can be collected.
Result: no memory leaks even if you forget to clean up entries manually.

Strong vs Weak References

The fundamental difference is whether a reference keeps an object alive in memory. A regular Map holds strong references — its keys and values will never be garbage-collected as long as the Map itself exists. A WeakMap holds weak references — keys can be reclaimed once no strong reference to them remains:

Map — Strong Reference
Map holds a strong ref to the key object
Even if your code sets the variable to null…
…the Map still holds the object alive
Memory is NOT freed until the Map is cleared or the entry deleted
Risk: memory leak if keys accumulate
WeakMap — Weak Reference
WeakMap holds only a weak ref to the key object
If your code sets the variable to null…
…no strong reference remains → object is eligible for GC
The WeakMap entry disappears automatically
Result: zero memory leak risk
// ── Map keeps objects alive forever ───────────────────────
const cache = new Map();
let obj = { id: 1 };
cache.set(obj, "data");
obj = null; // ❌ object NOT collected — Map still holds strong ref

// ── WeakMap lets GC reclaim the object ────────────────────
const wCache = new WeakMap();
let obj2 = { id: 2 };
wCache.set(obj2, "data");
obj2 = null; // ✅ object IS eligible for GC — WeakMap won't stop it
Map — strong ref, object survives WeakMap — weak ref, GC can reclaim Keys must be objects (not strings, numbers…) Entry disappears automatically on GC — no manual cleanup needed

WeakMap API

WeakMap has a deliberately minimal API — just four methods. There is no size property and no way to iterate over entries, because the set of live entries is non-deterministic (it depends on when the GC runs):

WeakMap Methods
1 wm.set(key, value) — stores value under key (key must be an object). Returns the WeakMap itself.
2 wm.get(key) — returns the value for key, or undefined if not present.
3 wm.has(key) — returns true if key exists in the WeakMap.
4 wm.delete(key) — removes the entry. Returns true if the key was present.
WeakSet Methods
1 ws.add(value) — adds an object to the set (must be an object). Returns the WeakSet itself.
2 ws.has(value) — returns true if the object is currently in the set.
3 ws.delete(value) — removes the object. Returns true if it was present.
✕ No size, no forEach, no keys(), no values() — WeakSet is intentionally non-iterable.
JavaScript — WeakMap & WeakSet API
// ── WeakMap ──────────────────────────────────────────────────
const wm = new WeakMap();

const keyA = {};                           // key must be an object
const keyB = {};

wm.set(keyA, "value for A");
wm.set(keyB, 42);

wm.get(keyA);                             // "value for A"
wm.has(keyB);                             // true
wm.delete(keyB);                         // true
wm.has(keyB);                             // false

// ❌ Primitives are NOT allowed as keys
wm.set("string", 1);                     // TypeError!

// ── WeakSet ──────────────────────────────────────────────────
const ws = new WeakSet();

const nodeA = document.createElement("div");
const nodeB = document.createElement("span");

ws.add(nodeA);
ws.add(nodeB);

ws.has(nodeA);                            // true
ws.delete(nodeB);                         // true
ws.has(nodeB);                            // false
Why no iteration?
The garbage collector can remove entries at any point in time. If you could iterate over a WeakMap, the list of entries could change mid-iteration in unpredictable ways. The spec deliberately omits size, forEach, keys(), and values() to prevent this. If you need iteration, use a regular Map or Set.

WeakMap vs Map — Full Comparison

Use this table to quickly decide which collection to reach for:

Feature Map WeakMap
Key types Any value Objects only
Reference type Strong — keeps key alive Weak — allows GC
size property ✓ Yes ✕ No
Iteration ✓ forEach, keys, values, entries ✕ Not iterable
clear() ✓ Yes ✕ No
Memory leaks Risk if keys accumulate None — entries auto-evict
Best for General-purpose key/value store Metadata keyed by object lifetime
Feature Set WeakSet
Value types Any value Objects only
Reference type Strong Weak — allows GC
size property ✓ Yes ✕ No
Iteration ✓ forEach, for...of ✕ Not iterable
Best for Unique value collections Tagging objects without preventing GC

Pattern — Private Data with WeakMap

Before ES2022 private class fields (#field), the standard pattern for truly private instance data was a module-scoped WeakMap. The key is the instance; the value is an object holding all private state:

// ❌ PROBLEM: using a closure-per-instance wastes memory
function Counter() {
  let _count = 0; // closure var — one copy per instance
  this.inc = () => _count++;
  this.get = () => _count;
}
JavaScript — Private Data via WeakMap
// ✅ Module-scoped WeakMap — private data, auto-cleaned on GC
const _private = new WeakMap();

class BankAccount {
  constructor(owner, balance) {
    _private.set(this, { owner, balance });
  }

  deposit(amount) {
    if (amount <= 0) throw new RangeError("Must be positive");
    _private.get(this).balance += amount;
  }

  getBalance() {
    return _private.get(this).balance;
  }

  getOwner() {
    return _private.get(this).owner;
  }
}

const acc = new BankAccount("Alice", 1000);
acc.deposit(500);
acc.getBalance();                        // 1500
acc.balance;                             // undefined — truly private!

// When acc goes out of scope, _private entry is GC'd automatically
Modern Alternative
ES2022 private class fields (#balance) are now the preferred way to write private data in new code — they are part of the language syntax and slightly simpler. The WeakMap pattern is still useful when you need to share private state across multiple cooperating classes or functions in the same module.

Key Method Reference

The complete API for both collections is tiny by design — here is every method with a one-line explanation:

new WeakMap()
Creates an empty WeakMap. Optionally accepts an iterable of [key, value] pairs where keys are objects (e.g., entries from another Map).
wm.set(key, value)
Associates value with key. key must be an object or a non-registered Symbol — passing a primitive throws a TypeError. Returns the WeakMap for chaining.
wm.get(key)
Returns the value associated with key, or undefined if the key is not present (or has already been garbage-collected).
wm.has(key)
Returns true if key is currently in the WeakMap — false otherwise. Useful as a guard before calling get().
wm.delete(key)
Removes the entry for key. Returns true if the key was present, false otherwise. Typically unnecessary — entries self-evict when the key is GC'd.
new WeakSet()
Creates an empty WeakSet. Optionally accepts an iterable of objects as initial values.
ws.add(value)
Adds value (must be an object) to the set. Duplicate adds are silently ignored — like regular Set. Returns the WeakSet for chaining.
ws.has(value) / ws.delete(value)
has returns a boolean indicating membership. delete removes the value and returns true if it was present. Neither throws if the value has already been garbage-collected.
Advertisement
📢 Ad space · 728 × 90 · Replace slot ID above

Real-World Use Cases

These are the everyday scenarios where WeakMap and WeakSet genuinely outperform their regular counterparts:

Private Instance Data
Store private properties of a class instance keyed by this. Data is inaccessible outside the module and auto-cleared when the instance is GC'd.
WeakMap
DOM Node Caching
Cache computed results (positions, dimensions, render state) keyed by DOM nodes. When nodes are removed from the page and GC'd, the cache entries vanish automatically — no cleanup code needed.
WeakMap
Visited / Processed Tracking
Mark objects as "already processed" in an algorithm (e.g., deep clone, cycle detection, graph traversal) using a WeakSet — no cleanup code required after the algorithm finishes.
WeakSet
Object Branding / Validation
Tag objects created by a specific factory or constructor (brand-checking) — call ws.has(obj) to verify an object was created by your code, not forged by a caller.
WeakSet
Memoization (Object Args)
Cache function results keyed by their object arguments. Unlike a regular Map, entries vanish when the argument objects go out of scope — preventing unbounded cache growth.
WeakMap
Lifecycle / Finalisation Hints
Track whether an object is "active" (e.g., a WebSocket connection, a mounted component) without preventing GC. When it's gone, wm.has(obj) returns false naturally.
WeakMap / WeakSet
⚡
Free Resource
Download our JavaScript Cheat Sheet
WeakMap, WeakSet, Map & Set — all on one page.
Get Sheet

Try It — Live Editor

Experiment with WeakMap below. The demo shows a DOM-node metadata cache — each button click creates a node, stores metadata in a WeakMap, then removes the node to let GC reclaim both the node and its WeakMap entry.

Live Editor
✎ Editor
👁 Preview

Common Patterns

Three patterns you'll encounter WeakMap and WeakSet used for in real codebases:

JavaScript — Pattern 1: Cycle Detection with WeakSet
// Deep-clone an object, safely handling circular references
function deepClone(obj, seen = new WeakSet()) {
  if (obj === null || typeof obj !== "object") return obj;
  if (seen.has(obj)) return "[Circular]";
  seen.add(obj);

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

const a = { x: 1 };
a.self = a;                                // circular ref!
deepClone(a);                             // { x: 1, self: "[Circular]" }
JavaScript — Pattern 2: Object Branding with WeakSet
// Verify objects were created by YOUR factory, not forged
const _trusted = new WeakSet();

function createUser(name, role) {
  const user = Object.freeze({ name, role });
  _trusted.add(user);                      // brand it
  return user;
}

function isValidUser(obj) {
  return _trusted.has(obj);               // check brand
}

const alice = createUser("Alice", "admin");
const fake = { name: "Hacker", role: "admin" };  // forged

isValidUser(alice);                         // true ✅
isValidUser(fake);                          // false ✅
JavaScript — Pattern 3: Memory-safe Memoization
// Cache results keyed by object argument — entries auto-evict
const cache = new WeakMap();

function processElement(el) {
  if (cache.has(el)) {
    console.log("cache hit");
    return cache.get(el);
  }
  const result = {
    rect: el.getBoundingClientRect(),
    styles: getComputedStyle(el),
  };
  cache.set(el, result);                    // store result
  return result;
}

// When the element is removed from the DOM and GC'd,
// the cache entry disappears automatically — no Map.clear() needed.
When to Use WeakMap vs Map
Use WeakMap when (1) your keys are objects, (2) those objects have their own lifetime that is not controlled by your code (e.g., DOM nodes, class instances, third-party objects), and (3) you want the associated data to disappear automatically when the key is gone. Use a regular Map for everything else — especially when you need to know how many entries you have or need to iterate over them.
Quick Check
Which of the following can be used as a key in a WeakMap?
Quick Check
Why do WeakMap and WeakSet not have a size property or iteration methods?
Chapter Summary
  • A weak reference does not prevent garbage collection. Once the only reference to an object is a WeakMap key or WeakSet member, that object can be reclaimed — and the entry disappears automatically.
  • WeakMap stores key/value pairs where keys must be objects (or non-registered Symbols). API: set, get, has, delete — nothing else.
  • WeakSet stores a collection of unique objects. API: add, has, delete — nothing else.
  • Neither collection has size, forEach, or iteration methods — entries can vanish at any time during GC, making a consistent snapshot impossible.
  • Choose WeakMap over Map when keys are objects with their own lifetime and you want zero memory-leak risk. Choose Map when you need to iterate, count, or use primitive keys.
  • Classic WeakMap pattern: private class data — store instance-private state in a module-scoped WeakMap keyed by this.
  • Classic WeakSet patterns: cycle detection (deep clone / serialise), object branding (verify trusted origin), and visited-node tracking in graph algorithms.
  • ES2022 private class fields (#prop) replace the WeakMap private-data pattern for most new code — but WeakMap remains superior when sharing private state across multiple cooperating classes.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel