0Pricing
JavaScript Academy · Lesson

WeakMap & WeakSet — simple privacy and caches

Learn WeakMap/WeakSet essentials: object-only keys, no size/iteration, privacy helpers, and tiny caches that auto-clean.

Why Weak collections?

Goal: Add metadata to objects without preventing garbage collection.

  • WeakMap: object → value
  • WeakSet: object membership
  • No size, no iteration
  • Great for privacy & caches
WeakMap & WeakSet — simple privacy and caches — illustration 1

WeakMap essentials

WeakMap only accepts object keys; supports set/get/has/delete; no iteration or size.

// WeakMap: keys must be objects
const wm = new WeakMap();

const user = { name: "Ayla" };
wm.set(user, { visits: 1 });

console.log("has user?", wm.has(user));
console.log("get meta:", wm.get(user));

// Note: no wm.size, no wm.keys() — not iterable
WeakMap & WeakSet — simple privacy and caches — illustration 2

All lessons in this course

  1. Map & Set essentials
  2. WeakMap & WeakSet — simple privacy and caches
  3. Iteration Patterns
← Back to JavaScript Academy