Useful Cheatsheetsusefulcheatsheets.com
JavaScript WeakMap and WeakRef
Chapter 36 · Page 284
Advanced

JavaScript WeakMap and WeakRef

Store object-keyed data and hold references without blocking garbage collection in JavaScript.

TL;DR

  1. 01Store object-keyed properties using weak references to support garbage collection.
  2. 02Hold object references without preventing the engine garbage collection process.
  3. 03Use FinalizationRegistry objects to configure cleanup callbacks for collected references.

Tips

  1. 01Attach metadata records to external object keys safely using self-cleaning WeakMap caches.
  2. 02Create memory-sensitive caches using WeakRef to let engines collect references under pressure.

Warnings

  1. 01Avoid setting primitive keys on WeakMap because keys must always be object references.
  2. 02Do not rely on FinalizationRegistry for critical updates since callback execution timing is unpredictable.
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript WeakMap and WeakRef
Chapter 36 · Page 285
Advanced

JavaScript WeakMap and WeakRef

(continued)

What WeakMap Is

  • WeakMap key values

    Stores key-value entries where keys are object references.

    const cache = new WeakMap();
    const user = { id: 1 };
    cache.set(user, { clicks: 3 });
  • Weak references

    Allows garbage collection of key objects when references disappear.

    let el = document.querySelector("#widget");
    cache.set(el, { clicks: 0 });
    el = null; // entry can be collected now
  • Key constraints

    Requires object keys, throwing errors when primitives are passed.

    // cache.set("key", 1); // TypeError
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript WeakMap and WeakRef
Chapter 36 · Page 286
Advanced

JavaScript WeakMap and WeakRef

(continued)

Non-Enumerable design

  • No iteration

    Prohibits access to size, keys, and values properties.

    const wm = new WeakMap();
    console.log(wm.size); // undefined
    // [...wm]; // TypeError: wm is not iterable
  • Deterministic safety

    Hides garbage collector actions to keep behavior predictable.

    // Non-enumerable design prevents observation
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript WeakMap and WeakRef
Chapter 36 · Page 287
Advanced

JavaScript WeakMap and WeakRef

(continued)

Private Data Caches

  • Property encapsulation

    Attaches private attributes to objects without changing structures.

    const privateData = new WeakMap();
    class Account {
      constructor(b) { privateData.set(this, { b }); }
      getBal() { return privateData.get(this).b; }
    }
  • Metadata attachment

    Caches calculated values keyed to specific element instances.

    const sizeCache = new WeakMap();
    function getBounding(el) {
      if (!sizeCache.has(el)) {
        sizeCache.set(el, el.getBoundingClientRect());
      }
      return sizeCache.get(el);
    }
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript WeakMap and WeakRef
Chapter 36 · Page 288
Advanced

JavaScript WeakMap and WeakRef

(continued)

WeakRef

  • Object wrappers

    Wraps object references without blocking garbage collection.

    let obj = { data: "large" };
    const ref = new WeakRef(obj);
    ref.deref(); // { data: "large" }
  • deref() checks

    Queries deref references, verifying presence before accesses.

    obj = null;
    // after GC executes:
    const target = ref.deref();
    if (target) console.log(target.data);
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript WeakMap and WeakRef
Chapter 36 · Page 289
Advanced

JavaScript WeakMap and WeakRef

(continued)

FinalizationRegistry

  • Cleanup callbacks

    Registers callbacks to execute after objects are collected.

    const reg = new FinalizationRegistry(held => {
      console.log("collected:", held);
    });
    reg.register(obj, "label");
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript WeakMap and WeakRef
Chapter 36 · Page 290
Advanced

JavaScript WeakMap and WeakRef

(FAQ)

FAQ

Map objects retain strong references to their keys, preventing garbage collection. WeakMap objects hold weak references, allowing keys to be collected. Keys must be objects, and iteration is prohibited.

Garbage collection timing is non-deterministic. Exposing entry lists would reveal when memory recovery occurred. The specification prohibits size and iteration properties to prevent engine leakage.

A WeakRef holds object references without preventing garbage collection. Call .deref() to retrieve targets. This method returns undefined if the object has already been garbage collected.

Use private fields for instance attributes on classes you write. Reach for WeakMap to store private data on foreign instances or plain objects that do not support private fields.

No, engines may skip callbacks if programs exit early. Treat these execution routines as non-critical optimizations. Always use explicit cleanups or try/finally blocks for essential operations.

Useful Cheatsheetsusefulcheatsheets.com
JavaScript WeakMap and WeakRef
Chapter 36 · Page 291
Advanced

JavaScript WeakMap and WeakRef

(In Practice)
In Practice

DOM Element Bounding Rect Cache

Caches DOM bounding rectangles using a WeakMap to automatically purge cache data when nodes are removed.

  1. 01Create a WeakMap instance to hold the DOM element cache.
  2. 02Check if the cache contains bounding rects for the query element.
  3. 03Calculate bounds using the element's bounding rect API.
  4. 04Store calculated bounds in the cache mapped to the element.
  5. 05Return cached bounds directly without executing repetitive calculations.
function createBoundingCache() {
  const cache = new WeakMap();

  function getBounds(element) {
    if (!cache.has(element)) {
      const rect =
        element.getBoundingClientRect();
      cache.set(element, rect);
    }
    return cache.get(element);
  }

  return { getBounds };
}
Takeaway

WeakMap structures automatically clean up cached entries once mapped element nodes are deleted from the DOM.