Hiprup

What are WeakMap and WeakSet used for?

Weak collections hold objects without preventing their garbage collection, which helps avoid memory leaks.

  • Private data — attach hidden state to an object via a WeakMap, keyed by the object itself.

  • Caching / metadata — associate data with objects that's cleaned up automatically when they're gone.

  • Tracking — a WeakSet can mark which objects have been seen, without keeping them alive.

Trade-off: because entries vanish when the key is collected, weak collections aren't iterable and have no size.

// WeakMap for private data
const privateData = new WeakMap();

class User {
  constructor(name, token) {
    privateData.set(this, { token }); // Truly private!
  }
  getToken() {
    return privateData.get(this).token;
  }
}

let user = new User('John', 'abc123');
console.log(user.getToken()); // 'abc123'
user = null; // User GC'd → WeakMap entry auto-removed!

// WeakSet for tracking
const processed = new WeakSet();
function processOnce(obj) {
  if (processed.has(obj)) return;
  processed.add(obj);
  // Process...
}

WeakMap stores private token data keyed by the User instance. When the user is garbage collected, the WeakMap entry is automatically removed (no memory leak).

WeakSet tracks processed objects — when objects are GC'd, entries are cleaned up automatically.

Weak references = no memory leak prevention. Keys/values auto-removed when GC'd. WeakMap for private data (keyed by this).

WeakSet for tracking objects. Neither is iterable (no size, no forEach). Use when you need to associate data with objects without preventing their cleanup.

What are WeakMap and WeakSet used for? | Hiprup