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.

WeakMap & WeakSet — simple privacy and caches is a free JavaScript Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

WeakSet essentials

WeakSet holds objects; no duplicates, no iteration, no size property.

// WeakSet: store objects without duplicates
const ws = new WeakSet();

const obj1 = {};
const obj2 = {};

ws.add(obj1);
ws.add(obj2);
ws.add(obj1); // duplicate ignored

console.log("has obj1?", ws.has(obj1));

// Note: no ws.size and no iteration
WeakMap & WeakSet — simple privacy and caches — illustration 3

Privacy via WeakMap

Use a WeakMap to attach hidden data to API objects; when API objects are gone, data can be collected.

// Privacy helper: store private data outside the object
const _priv = new WeakMap();

function makeCounter() {
  const api = {};
  _priv.set(api, { value: 0 });

  api.inc = function () {
    const box = _priv.get(api);
    box.value = box.value + 1;
    console.log("value", box.value);
  };

  // No public field exposes value directly
  return api;
}

const c = makeCounter();
c.inc();
c.inc();
// console.log(c.value) -> undefined (nothing public)
WeakMap & WeakSet — simple privacy and caches — illustration 4

Per-object cache

Create a per-object cache; entries vanish when the key object is no longer referenced.

// Cache computed data per object without leaks
const cache = new WeakMap();

function computeLength(doc) {
  // Return cached result if present
  if (cache.has(doc)) {
    return cache.get(doc);
  }
  // Fake "expensive" compute
  const result = (doc.text || "").length;
  cache.set(doc, result);
  return result;
}

const d1 = { text: "hello" };
const d2 = { text: "world!" };

console.log("len d1:", computeLength(d1));
console.log("len d1 cached:", computeLength(d1));
console.log("len d2:", computeLength(d2));

// If d1/d2 become unreachable, their cache entries can disappear automatically
WeakMap & WeakSet — simple privacy and caches — illustration 5

Limits & when not to use

Remember:

  • No iteration or size on WeakMap/WeakSet.
  • Keys must be objects.
  • Use Map/Set if you need to list keys or count items.
WeakMap & WeakSet — simple privacy and caches — illustration 6

WeakMap vs Map quiz

Quick check: WeakMap use case.

WeakMap & WeakSet — simple privacy and caches — illustration 7

Recap

Recap: Use WeakMap for object→value privacy and caches; use WeakSet for object membership without leaks. Remember: object keys only, no iteration or size.

WeakMap & WeakSet — simple privacy and caches — illustration 8

Frequently asked questions

Is the “WeakMap & WeakSet — simple privacy and caches” lesson free?

Yes — the full text of “WeakMap & WeakSet — simple privacy and caches” is free to read here on the web, and the JavaScript Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “WeakMap & WeakSet — simple privacy and caches”?

Learn WeakMap/WeakSet essentials: object-only keys, no size/iteration, privacy helpers, and tiny caches that auto-clean. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start JavaScript Academy?

No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “WeakMap & WeakSet — simple privacy and caches” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this JavaScript Academy lesson?

Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

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