Ch. 1 · JavaScript

JavaScript WeakMap and Object Lifetimes

JavaScript WeakMap and Object Lifetimes. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

WeakMaps attach metadata without keeping object keys alive solely through the map. They fit metadata tied to another object’s lifetime, rather than enumerable caches.

Step-by-step walkthrough

Step 1: Tie metadata to an existing object

A WeakMap fits metadata that should live no longer than an externally owned object. The association itself should not be the reason that object remains strongly reachable. It is not a general enumerable collection of business IDs.

Step 2: Select the actual key

Use the real object whose lifetime matters, such as a DOM node or model instance. A newly created lookalike object is a different key. Stable string identifiers instead call for a Map with explicit deletion or expiration.

Step 3: Avoid collection-timing logic

Garbage collection is nondeterministic. Application correctness must not depend on observing precisely when an entry vanishes. WeakMap intentionally lacks enumeration and size, so build diagnostics around explicit operations rather than trying to inspect collectible entries.

Worked scenario

Validation metadata stored under a DOM element can become collectible when the element has no remaining strong owners.

const metadata = new WeakMap();
const model = {id: 'u1'};
metadata.set(model, {validated: true});
console.log(metadata.get(model).validated); // true
console.log(metadata.get({id: 'u1'})); // undefined
metadata.delete(model);
console.log(metadata.has(model)); // false
JavaScript

Walk through the example

The key is the model reference, not its ID field. Deletion is explicit and observable, while eventual collection after all external references disappear is not a scheduling guarantee. The value can contain metadata needed by the model owner without requiring an additional globally indexed cache entry.

Common mistake

Collection timing is not a dependable event. WeakMaps do not offer iteration or size.

Verify the behavior

Test lookup with the original object and a separate equal-looking object. Verify explicit deletion. Do not write a test requiring garbage collection at a particular instant; that tests runtime scheduling instead of the public lifetime contract.

Interview exercise

Cache by string user ID.

Answer and reasoning

Use a Map with explicit eviction; strings are not weak keys, and shared caches usually require visible lifetime management.

Follow-up discussion

Can WeakMap report how many objects remain? No, and that is consistent with not exposing garbage-collection timing. Should it cache API results by user ID? Usually not: string-keyed shared caches need explicit expiry, limits and observability, which a Map or dedicated cache can provide.

Continue learning

Compare the scenario with the JavaScript interview questions and test your understanding with the JavaScript MCQs. For terminology and implementation details, consult the reference material.

More in JavaScript

read ✓JavaScript · mid

JavaScript Date and Timezone Pitfalls

Parse and format dates without timezone surprises: zero-based months, date-only versus date-time parsing, and why UTC storage avoids drift.

~3 min readread →
read ✓JavaScript · mid

JavaScript Number Precision and BigInt

Why 0.1 + 0.2 is not 0.3, where safe integer range ends, and when BigInt is the right tool for large identifiers and money.

~2 min readread →
esc