Course contentsShow
← JavaScript
Lesson 532 of 2,72313. ClosuresFree lesson

Closures vs Weak References

Understanding when WeakMap and WeakSet help avoid memory issues that closures can cause.

Closures vs Weak References

You'll learn when WeakMap and WeakSet help prevent memory leaks that closures can accidentally create.

The Memory Problem Closures Create

Closures keep their captured variables alive for as long as the closure function exists. This is usually helpful, but sometimes it creates unintended memory retention. If you store large objects in a closure's scope and keep references to those closures around (like in event listeners or caches), those objects can never be garbage collected—even if nothing else needs them.

Enter Weak References

JavaScript provides WeakMap and WeakSet specifically for situations where you want to associate data with objects without preventing those objects from being garbage collected. Unlike closures that hold strong references, weak references allow the garbage collector to clean up objects when they're no longer used elsewhere.

When to Choose Which

Use closures when you genuinely need to preserve data for the lifetime of your function. Use WeakMap/WeakSet when you're storing metadata about objects that should be cleaned up automatically when those objects are no longer needed.

For example: attaching private data to DOM elements with closures means those elements stay in memory even after removal from the page. Using a WeakMap instead lets the browser clean up both the element and your data when the element is removed.

// Closure holds strong reference
const privateData = new Map();
element.addEventListener('click', () => {
  privateData.set(element, data); // element can't be garbage collected
});

// WeakMap allows cleanup
const privateData = new WeakMap();
element.addEventListener('click', () => {
  privateData.set(element, data); // element can be collected when removed
});

Key Takeaway: Use closures for intentional state preservation; use WeakMap/WeakSet when you need temporary associations that shouldn't prevent garbage collection.