Compile Ready
Module 11 · Advanced JavaScript

WeakMap

Advanced12m read18m practice30m total
WeakMapGarbage CollectionPrivate DataObject Identity

Introduction

A WeakMap stores key-value pairs where keys must be objects and those keys are held weakly. If nothing else references a key object, the garbage collector may remove it and its associated value.

WeakMap is not a smaller Map. It is a specialized structure for associating metadata with object identities without preventing garbage collection.

Why This Matters

WeakMap shows up in interviews around memory leaks, private data, metadata, memoization by object identity, and cycle detection. It proves that you understand reachability and why enumeration is intentionally impossible.

Theory

Weak keys

Only objects can be keys in a WeakMap. Primitive keys throw TypeError. The weak part means the map does not keep the key alive. If the key becomes unreachable elsewhere, its entry can disappear.

No enumeration

WeakMap has no keys, values, entries, forEach, or size. If enumeration were allowed, observing garbage collection would become possible and nondeterministic.

Private data pattern

WeakMap is a common way to store per-instance private state outside the instance object. The instance is the key; private data is the value.

Metadata without leaks

WeakMap is ideal for caching metadata about objects you do not own: validation state, parsed AST info, observer records, or clone bookkeeping. When the object is gone, the metadata can go too.

Visual Diagrams

Weak association
object key <---- app reference
   |
WeakMap stores metadata

when app reference disappears:
object key can be collected
WeakMap entry can vanish

The WeakMap does not count as a strong reference to the key.

Code Examples

Private state with WeakMap

The state cannot be reached through instance properties or enumeration.

Loading…

Playground

Loading editor…
Console

Press Run to execute the code and see output here.

Output Prediction

Predict the output #1

javascript
1var weak = new WeakMap();
2var a = { id: 1 };
3var b = { id: 1 };
4
5weak.set(a, 'first');
6
7console.log(weak.get(a));
8console.log(weak.get(b));
9console.log(weak.has(a));
10
11try {
12 weak.set('x', 1);
13} catch (error) {
14 console.log(error.name);
15}

Coding Exercises

Build a private counter using WeakMap

Medium

Implement a Counter class whose count cannot be read through public object properties. Use a module-level WeakMap for private state with increment, decrement, and value methods.

Interview Questions

1Why can you not iterate over a WeakMap?

WeakMap entries may disappear whenever keys become unreachable, and garbage collection timing is intentionally not observable. Enumeration or size would expose GC behavior and make programs nondeterministic.

Asked at:GoogleMetaMicrosoft

Follow-ups

  • Why must keys be objects?
  • When would `Map` be better?
2Give a real use case for WeakMap.

Store metadata or private state for object instances without preventing those objects from being garbage-collected. Examples include private class state, clone bookkeeping, AST metadata, and memoizing results by object identity.

Quiz

1. Which operation is available on `WeakMap`?

Summary

  • WeakMap keys must be objects and are held weakly.
  • WeakMap does not expose enumeration or size.
  • Use WeakMap for private state and metadata that should not keep objects alive.
  • Use Map when you need primitive keys or iteration.

Cheat Sheet

API: set, get, has, delete.

Keys: objects only.

Weakness: key is not kept alive by the WeakMap.

No enumeration: no size, keys, values, entries.

Use cases: private data, metadata, cycle tracking, object-identity memoization.