Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

JS Puzzles · Const

WeakMap GC

WeakMap associates values with object keys without preventing those keys from being garbage-collected. Its entries cannot be enumerated, and cleanup timing is controlled by the JavaScript engine.

How it works

A WeakMap stores values under object keys without strongly retaining those keys. When a key has no other references, the engine may collect the key and its associated value; cleanup timing is implementation-dependent, and the collection cannot be enumerated.

Syntax

new WeakMap(); weakMap.set(key, value); weakMap.get(key); weakMap.has(key); weakMap.delete(key)

Parameters

NameTypeDescription
keyobjectThe object used as the weak key.
valueanyThe value associated with the key; it may be any JavaScript value.

Returns

WeakMap methods return the associated value, a boolean for has/delete, or the WeakMap instance for set; the page specifically lists get, set, delete, and has.

Key points

  • Unlike Map, WeakMap does not keep its object keys alive solely because they are keys.
  • A key can become collectible when no other strong reference reaches it.
  • When the key becomes unreachable elsewhere, its entry is eventually removed along with the key.
  • WeakMap is useful for attaching auxiliary data whose lifetime follows an object.
  • set(key, value) adds or replaces the value associated with an object key.
  • get(key) retrieves the value associated with the key.

Common mistakes

  • Do not rely on immediate cleanup: the JavaScript engine chooses when garbage collection occurs.
  • You cannot inspect all entries or use keys(), values(), or entries() to observe which keys remain.
  • Primitive values such as strings and numbers cannot be used as keys.

Example: Associate metadata without preventing collection

const metadata = new WeakMap();

let user = { name: "John" };
metadata.set(user, { lastLogin: new Date() });

console.log(metadata.get(user));
user = null; // The object and associated metadata may be collected later.

The metadata is associated with the object without keeping that object alive.

When to use it

Object metadata

Attach cached or computed metadata to objects without extending their lifetime.

Ephemeral associations

Store auxiliary data for objects managed by another collection or subsystem.

Leak-resistant caching

Avoid memory retention when associated objects become unreachable.

  • Map
  • WeakSet
  • garbage collection
  • weak references

Source: WeakMap and WeakSet. Checked 2026-10-15.