JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext

Learn the concept

Data Structures

javascript
mid
weakrefs

What are WeakMap and WeakSet, and how do they differ from Map and Set?

weakmap
weakset
garbage-collection
memory
data-structures
Quick Answer

WeakMap and WeakSet hold weak references to object keys/values, allowing garbage collection when no other references exist. Unlike Map and Set, they are not iterable and have no size property.

Detailed Explanation

WeakMap and WeakSet are specialized collections that hold weak references to objects. A weak reference does not prevent the garbage collector from reclaiming the object — if the only remaining reference to an object is through a WeakMap key or WeakSet entry, the object can be garbage collected.

WeakMap vs Map

| Feature | Map | WeakMap | |---------|-----|---------| | Key types | Any value (string, number, object) | Objects only (no primitives) | | Garbage collection | Keys prevent GC (strong reference) | Keys do NOT prevent GC (weak reference) | | Iterable | Yes (for...of, .forEach()) | No | | .size property | Yes | No | | .clear() method | Yes | No | | Methods | get, set, has, delete, entries, keys, values | get, set, has, delete only |

Why WeakMap Keys Must Be Objects

Primitive values (strings, numbers) are compared by value and can be recreated anywhere. The engine cannot track when "all references" to the number 42 are gone — the concept doesn't apply. Objects are compared by reference, so the engine knows exactly when no code can reach a specific object anymore.

Use Cases for WeakMap

  1. DOM element metadata — Store data associated with DOM nodes. When a node is removed from the document and no other code references it, both the node and its metadata are garbage collected:
JavaScript
const metadata = new WeakMap();
function trackElement(el) {
  metadata.set(el, { clickCount: 0, created: Date.now() });
}
// When el is removed from DOM and dereferenced, metadata is cleaned up
  1. Private instance data — Store truly private data for class instances without it being accessible through the instance:
JavaScript
const privateData = new WeakMap();
class User {
  constructor(name, password) {
    privateData.set(this, { password });
    this.name = name;
  }
  checkPassword(input) {
    return privateData.get(this).password === input;
  }
}
  1. Caching without memory leaks — Cache computed results keyed by objects. When the object is no longer needed, the cache entry is automatically cleaned up.

WeakSet Use Cases

WeakSet stores objects (not values) and is mainly used to tag objects without preventing garbage collection:

  • Mark objects as "visited" during graph traversal
  • Track which DOM nodes have been processed
  • Implement branding (check if an object was created by a specific constructor)

Key Interview Distinction

WeakMap/WeakSet exist to solve memory leaks. Regular Map/Set keep strong references — if you store an object as a Map key and forget to delete it, the object can never be garbage collected even if no other code uses it. WeakMap/WeakSet solve this by allowing the garbage collector to reclaim objects when they are no longer reachable through any strong reference.

Code Examples

WeakMap for DOM MetadataJavaScript
const clickCounts = new WeakMap();

document.querySelectorAll('button').forEach((btn) => {
  clickCounts.set(btn, 0);

  btn.addEventListener('click', () => {
    const count = clickCounts.get(btn) + 1;
    clickCounts.set(btn, count);
    console.log(`Button clicked ${count} times`);
  });
});

// If a button is removed from the DOM and dereferenced,
// its click count is automatically garbage collected.
// With a regular Map, you'd need to manually delete the entry.

Real-World Applications

Use Cases

DOM Metadata Tracking

Track scroll positions, click counts, or validation state for DOM elements without preventing garbage collection when elements are removed.

Framework Internal State

React and Vue use WeakMap internally to associate component state with fiber/VNode objects without creating memory leaks during component unmounting.

Mini Projects

Memoization with WeakMap

intermediate

Build a memoize function that caches results keyed by object arguments using WeakMap, ensuring cached entries are automatically cleaned up.

Industry Examples

Vue.js

Vue 3's reactivity system uses WeakMap to associate reactive proxies with their original objects, preventing memory leaks when components are destroyed.

Resources

MDN - WeakMap

docs

MDN - WeakSet

docs

JavaScript.info - WeakMap and WeakSet

article

Related Questions

How does JavaScript garbage collection work and how can you prevent memory leaks?

senior
memory

When should you use Map and Set instead of plain objects and arrays?

mid
data-structures
Previous
What is the difference between block scope and function scope?
Next
Explain event bubbling, capturing, and how stopPropagation works.
PrevNext