Skip to content

WeakMap

In one line

A WeakMap is a collection of key-value pairs where keys are objects and weakly held, allowing garbage collection.

In simple words

A WeakMap is like a Map, but its keys must be objects (or symbols) and are held weakly — if nothing else references a key object, the entry can be garbage collected. This prevents memory leaks when you want to attach extra data to objects you do not own.

Because keys can disappear at any time, WeakMap is not enumerable: there is no size, no keys(), no iteration. You can only get, set, has, and delete by a specific key. This is the trade-off for the memory-safety guarantee.

Use WeakMap to associate private data with objects (a common encapsulation pattern), to cache results per-object without leaking, or to add metadata to DOM nodes or third-party objects. The entry dies with the key object, automatically.

Example

javascript
const privateData = new WeakMap();

function makeObject(name) {
  const obj = {};
  privateData.set(obj, { name, createdAt: Date.now() });
  return obj;
}

const a = makeObject("Ada");
console.log(privateData.get(a).name); // "Ada"
// When `a` goes out of scope and is GC'd, the WeakMap entry is freed automatically

Private data is stored in a WeakMap keyed by the object. When the object is garbage collected, the entry is freed — no leak.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary