Course contentsShow
← JavaScript
Lesson 1059 of 2,72324. Maps and SetsFree lesson

WeakMap Use Case: Metadata and Caching

Associating metadata with DOM nodes or objects without preventing their cleanup.

WeakMap Use Case: Metadata and Caching

You'll learn how to attach metadata or cache results to objects without preventing garbage collection.

The Problem: Attaching Data Without Memory Leaks

Sometimes you need to associate extra information with objects—like tracking DOM nodes, caching computation results, or storing metadata—but you don't want to prevent those objects from being cleaned up when they're no longer needed elsewhere in your program.

If you use a regular Map, the objects become permanent keys that won't be garbage collected, even when nothing else references them. This creates memory leaks.

The WeakMap Solution

A WeakMap lets you attach data to objects without creating this permanent reference. When the object key is no longer used anywhere else in your code, both the key and its associated value can be garbage collected automatically.

Common use case: DOM node metadata

const nodeMetadata = new WeakMap();

function trackElement(element) {
  nodeMetadata.set(element, {
    clicks: 0,
    created: Date.now()
  });
}

function incrementClicks(element) {
  const data = nodeMetadata.get(element);
  if (data) data.clicks++;
}

// When the DOM element is removed and no longer referenced,
// the metadata is automatically cleaned up—no memory leak!

Common use case: Caching expensive computations

const computationCache = new WeakMap();

function expensiveOperation(obj) {
  if (computationCache.has(obj)) {
    return computationCache.get(obj); // Return cached result
  }
  
  const result = /* expensive calculation using obj */;
  computationCache.set(obj, result);
  return result;
}

The cache automatically cleans itself when objects are no longer needed—you don't have to manually clear old entries.

Key Takeaway: Use WeakMap when you need to associate metadata or cached data with objects without preventing their garbage collection—perfect for DOM nodes, temporary objects, or any scenario where you don't control the object lifecycle.