JavaScript WeakMap and WeakSet Complete Guide

Master JavaScript WeakMap and WeakSet for memory-efficient programming. Covers weak reference semantics, garbage collection interaction, private data storage, DOM metadata, caching with automatic cleanup, object tagging, circular reference handling, and comparison with Map and Set.

JavaScriptadvanced
17 min read

WeakMap and WeakSet hold weak references to objects, allowing them to be garbage collected when no other references exist. They solve the fundamental problem of associating data with objects without preventing their cleanup.

For related memory management patterns, see Preventing Memory Leaks with JS WeakMaps Guide.

WeakMap Fundamentals

javascriptjavascript
// WeakMap keys MUST be objects (or non-registered symbols)
// Keys are held weakly: if no other reference exists, they can be GC'd
// WeakMap is NOT iterable and has no .size property
 
const wm = new WeakMap();
 
// Setting key-value pairs
const objA = { id: 1 };
const objB = { id: 2 };
 
wm.set(objA, "data for A");
wm.set(objB, "data for B");
 
// Getting values
console.log(wm.get(objA)); // "data for A"
console.log(wm.has(objB)); // true
 
// Deleting entries
wm.delete(objB);
console.log(wm.has(objB)); // false
 
// WEAK REFERENCE BEHAVIOR
let tempObj = { id: 3 };
wm.set(tempObj, "temporary data");
 
console.log(wm.has(tempObj)); // true
 
// When we remove the only reference, the entry becomes eligible for GC
tempObj = null;
// The WeakMap entry for { id: 3 } will be garbage collected
// We cannot verify this directly (WeakMap is not iterable)
 
// WHAT CANNOT BE A WEAKMAP KEY:
// wm.set("string", "value");    // TypeError: Invalid value as weak map key
// wm.set(42, "value");          // TypeError
// wm.set(true, "value");        // TypeError
// wm.set(null, "value");        // TypeError
// wm.set(undefined, "value");   // TypeError
 
// WHAT CAN BE A WEAKMAP KEY:
wm.set({}, "plain object");
wm.set([], "array");
wm.set(function() {}, "function");
wm.set(new Date(), "date");
wm.set(/regex/, "regexp");
wm.set(Symbol("registered"), "symbol"); // Non-registered symbols only
 
// AVAILABLE METHODS (only 4):
// .get(key)    - retrieve value
// .set(key, value) - store value
// .has(key)    - check existence
// .delete(key) - remove entry
// No .size, no .keys(), no .values(), no .entries(), no .forEach()
// No iteration is possible by design

Private Data Storage

javascriptjavascript
// WeakMap is the classic pattern for truly private instance data
 
const _private = new WeakMap();
 
class SecureUser {
  constructor(name, password) {
    _private.set(this, {
      password: this.#hashPassword(password),
      loginAttempts: 0,
      lastLogin: null
    });
    this.name = name; // Public property
  }
 
  #hashPassword(pwd) {
    // Simplified hash for illustration
    let hash = 0;
    for (let i = 0; i < pwd.length; i++) {
      hash = ((hash << 5) - hash + pwd.charCodeAt(i)) | 0;
    }
    return hash.toString(16);
  }
 
  authenticate(password) {
    const data = _private.get(this);
    data.loginAttempts++;
 
    if (this.#hashPassword(password) === data.password) {
      data.lastLogin = new Date();
      data.loginAttempts = 0;
      return true;
    }
 
    if (data.loginAttempts >= 3) {
      throw new Error("Account locked: too many attempts");
    }
 
    return false;
  }
 
  getLastLogin() {
    return _private.get(this).lastLogin;
  }
 
  // When the SecureUser instance is garbage collected,
  // the WeakMap entry (including the password hash) is also collected
}
 
const user = new SecureUser("Alice", "secret123");
console.log(user.name);          // "Alice" (public)
console.log(user.authenticate("secret123")); // true
console.log(user.getLastLogin()); // Date object
 
// Cannot access private data externally:
// _private is module-scoped, not accessible from outside
// Even with access to _private, you need the object reference as key
 
// BENEFIT OVER #PRIVATE FIELDS:
// 1. Works with objects that are not class instances
// 2. Can store data on objects you don't own
// 3. Automatically cleans up when object is GC'd
// 4. Existed before #private fields (ES2015 vs ES2022)
 
// STORING PRIVATE DATA ON ANY OBJECT
const metadata = new WeakMap();
 
function attachMetadata(obj, data) {
  metadata.set(obj, { ...metadata.get(obj), ...data });
}
 
function getMetadata(obj) {
  return metadata.get(obj) || {};
}
 
const domNode = { tagName: "div" }; // Simulated DOM element
attachMetadata(domNode, { createdBy: "framework", timestamp: Date.now() });
attachMetadata(domNode, { renderCount: 0 });
 
console.log(getMetadata(domNode));
// { createdBy: "framework", timestamp: ..., renderCount: 0 }

WeakSet Fundamentals

javascriptjavascript
// WeakSet holds objects weakly (like WeakMap but without values)
// Used for tagging/marking objects without preventing GC
 
const ws = new WeakSet();
 
const obj1 = { id: 1 };
const obj2 = { id: 2 };
 
ws.add(obj1);
ws.add(obj2);
 
console.log(ws.has(obj1)); // true
console.log(ws.has(obj2)); // true
 
ws.delete(obj1);
console.log(ws.has(obj1)); // false
 
// AVAILABLE METHODS (only 3):
// .add(object)     - add to set
// .has(object)     - check membership
// .delete(object)  - remove from set
// No .size, no iteration
 
// PATTERN: Tracking visited objects (prevents infinite recursion)
function deepEqual(a, b, visited = new WeakSet()) {
  // Handle primitives
  if (a === b) return true;
  if (typeof a !== "object" || typeof b !== "object") return false;
  if (a === null || b === null) return false;
 
  // Circular reference check
  if (visited.has(a)) return true; // Already compared this object
  visited.add(a);
 
  const keysA = Object.keys(a);
  const keysB = Object.keys(b);
 
  if (keysA.length !== keysB.length) return false;
 
  for (const key of keysA) {
    if (!deepEqual(a[key], b[key], visited)) return false;
  }
 
  return true;
}
 
// Works with circular references
const circular = { value: 1 };
circular.self = circular;
 
const circular2 = { value: 1 };
circular2.self = circular2;
 
console.log(deepEqual(circular, circular2)); // true (no stack overflow)
 
// PATTERN: Instance branding (type checking)
const Brand = new WeakSet();
 
class ValidatedInput {
  constructor(value) {
    if (typeof value !== "string") {
      throw new TypeError("Value must be a string");
    }
    this.value = value;
    Brand.add(this);
  }
 
  static isValid(obj) {
    return Brand.has(obj);
  }
}
 
function processInput(input) {
  if (!ValidatedInput.isValid(input)) {
    throw new Error("Input must be a ValidatedInput instance");
  }
  return input.value.toUpperCase();
}
 
const valid = new ValidatedInput("hello");
console.log(processInput(valid)); // "HELLO"
 
// Fake objects fail the brand check
const fake = { value: "hello" };
// processInput(fake); // Error: Input must be a ValidatedInput instance

Caching with Automatic Cleanup

javascriptjavascript
// WeakMap cache: entries are automatically removed when keys are GC'd
 
class ComputeCache {
  #cache = new WeakMap();
 
  compute(input, expensiveFn) {
    if (this.#cache.has(input)) {
      return this.#cache.get(input);
    }
 
    const result = expensiveFn(input);
    this.#cache.set(input, result);
    return result;
  }
 
  invalidate(input) {
    this.#cache.delete(input);
  }
}
 
const cache = new ComputeCache();
 
function analyzeDocument(doc) {
  return cache.compute(doc, (d) => {
    // Expensive analysis
    const words = d.content.split(/\s+/).length;
    const chars = d.content.length;
    const sentences = d.content.split(/[.!?]+/).length;
    return { words, chars, sentences, readingTime: Math.ceil(words / 200) };
  });
}
 
let doc1 = { title: "Article", content: "This is a long document with many words." };
 
console.log(analyzeDocument(doc1)); // Computed
console.log(analyzeDocument(doc1)); // Cached (same object reference)
 
// When doc1 is no longer referenced, the cache entry is GC'd automatically
doc1 = null; // Cache entry eligible for garbage collection
 
// MULTI-KEY WEAK CACHE
// For caching based on multiple object arguments
class MultiKeyWeakCache {
  #primary = new WeakMap();
 
  get(key1, key2) {
    const secondary = this.#primary.get(key1);
    if (!secondary) return undefined;
    return secondary.get(key2);
  }
 
  set(key1, key2, value) {
    let secondary = this.#primary.get(key1);
    if (!secondary) {
      secondary = new WeakMap();
      this.#primary.set(key1, secondary);
    }
    secondary.set(key2, value);
  }
 
  has(key1, key2) {
    const secondary = this.#primary.get(key1);
    return secondary ? secondary.has(key2) : false;
  }
}
 
const relCache = new MultiKeyWeakCache();
const userObj = { name: "Alice" };
const roleObj = { name: "admin" };
 
relCache.set(userObj, roleObj, { permissions: ["read", "write", "delete"] });
console.log(relCache.get(userObj, roleObj));
// { permissions: ["read", "write", "delete"] }

DOM Element Metadata

javascriptjavascript
// Attach data to DOM elements without modifying them
// When elements are removed from DOM and GC'd, data is cleaned up
 
const elementData = new WeakMap();
 
function setElementData(element, key, value) {
  if (!elementData.has(element)) {
    elementData.set(element, {});
  }
  elementData.get(element)[key] = value;
}
 
function getElementData(element, key) {
  const data = elementData.get(element);
  return data ? data[key] : undefined;
}
 
function removeElementData(element) {
  elementData.delete(element);
}
 
// Usage (in browser context):
// const button = document.createElement('button');
// setElementData(button, 'clickCount', 0);
// setElementData(button, 'handler', (e) => {
//   const count = getElementData(button, 'clickCount') + 1;
//   setElementData(button, 'clickCount', count);
// });
//
// When button is removed from DOM and dereferenced,
// all associated data is automatically GC'd
 
// EVENT DELEGATION WITH WEAKMAP
class EventDelegator {
  #handlers = new WeakMap();
 
  register(element, eventType, handler) {
    if (!this.#handlers.has(element)) {
      this.#handlers.set(element, new Map());
    }
    const elementHandlers = this.#handlers.get(element);
 
    if (!elementHandlers.has(eventType)) {
      elementHandlers.set(eventType, []);
    }
    elementHandlers.get(eventType).push(handler);
  }
 
  dispatch(element, eventType, event) {
    const elementHandlers = this.#handlers.get(element);
    if (!elementHandlers) return;
 
    const handlers = elementHandlers.get(eventType);
    if (!handlers) return;
 
    for (const handler of handlers) {
      handler(event);
    }
  }
 
  cleanup(element) {
    this.#handlers.delete(element);
    // Or just let GC handle it when element is dereferenced
  }
}
 
const delegator = new EventDelegator();
 
// TRACKING PROCESSED ELEMENTS WITH WEAKSET
const initialized = new WeakSet();
 
function initializeWidget(element) {
  if (initialized.has(element)) {
    return; // Already initialized
  }
 
  // Setup the widget
  element.dataset = element.dataset || {};
  element.dataset.initialized = "true";
 
  initialized.add(element);
}
 
const el = { tagName: "div" };
initializeWidget(el);
initializeWidget(el); // No-op (already initialized)
FeatureMapWeakMapSetWeakSet
Key typesAnyObjects onlyAnyObjects only
IterableYesNoYesNo
Size propertyYesNoYesNo
GC of keysNo (strong ref)Yes (weak ref)N/AYes (weak ref)
Use caseGeneral storageObject metadataUnique valuesObject tagging
forEachYesNoYesNo
clear()YesNoYesNo
Rune AI

Rune AI

Key Insights

  • WeakMap keys are held weakly, allowing garbage collection of entries when no other references to the key exist: This prevents memory leaks for object-associated data
  • WeakMap is ideal for private data storage because module-scoped WeakMaps are inaccessible from outside and automatically clean up: This pattern predates private class fields and works with any object
  • WeakSet enables efficient object tagging for tasks like circular reference detection and initialization tracking: The has() check is O(1) and entries clean up automatically
  • Neither WeakMap nor WeakSet support iteration, size checks, or clearing because weak references can be collected at any time: This is a deliberate design constraint, not a limitation
  • Use WeakMap for caching when cache entries should not prevent garbage collection of the key objects: This eliminates the need for manual cache eviction and prevents unbounded memory growth
RunePowered by Rune AI

Frequently Asked Questions

Why can't WeakMap keys be primitives?

Primitives (strings, numbers, booleans) do not have identity; they are compared by value. The number `42` is always `42` regardless of where it appears. Weak references require identity-based tracking because the garbage collector needs to know when a specific object instance is no longer reachable. Since primitives are not allocated on the heap as distinct instances, there is no meaningful concept of "garbage collecting" a primitive value. Objects have distinct identity and heap allocation, making them suitable for weak reference tracking.

How do I know when a WeakMap entry has been collected?

You cannot directly observe when a WeakMap entry is garbage collected. WeakMap has no size property, no iteration, and no callbacks for entry removal. If you need cleanup notifications, use FinalizationRegistry (ES2021), which calls a callback when a registered object is garbage collected. However, FinalizationRegistry callbacks are not guaranteed to run promptly (or at all), so do not rely on them for critical cleanup logic. Design your code to work correctly regardless of when GC occurs.

When should I use WeakMap instead of Map?

Use WeakMap when you are associating data with objects you do not own or control the lifecycle of (DOM elements, third-party objects, framework instances). Use WeakMap when the associated data should not prevent the object from being garbage collected. Use regular Map when keys are primitives, when you need to iterate over entries, when you need a size count, or when you want to keep keys alive. If you are storing object metadata and the number of objects can grow unboundedly, WeakMap prevents memory leaks.

Can WeakRef replace WeakMap for caching?

WeakRef (ES2021) provides a different weak reference mechanism. WeakRef gives you a reference to an object that does not prevent GC, and you check if it is still alive with `.deref()`. WeakMap provides key-value association where the key is weak. For simple caching where you want to check if a value still exists, WeakRef works. For associating data with objects (private data, metadata, DOM data), WeakMap is the right tool because it automatically cleans up both the key and associated value. WeakRef requires manual cleanup of associated data.

Conclusion

WeakMap and WeakSet provide memory-safe data association through weak references. WeakMap excels at private data storage, caching, and DOM metadata. WeakSet handles object tagging and circular reference detection. Both automatically clean up when their keys are garbage collected. For preventing memory leaks with these tools, see Preventing Memory Leaks with JS WeakMaps Guide. For understanding how the Proxy API uses WeakMap for private data, explore Advanced JavaScript Proxies Complete Guide.