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

When to Use Weak vs Strong Collections

Deciding between Map/Set and WeakMap/WeakSet based on lifecycle and iteration needs.

When to Use Weak vs Strong Collections

You'll learn how to choose between Map/Set and WeakMap/WeakSet based on your program's needs.

Understanding the Choice

Think of strong collections (Map/Set) as permanent filing cabinets where you control what stays and what goes. Weak collections (WeakMap/WeakSet) are like temporary sticky notes that automatically disappear when the thing they reference is no longer needed elsewhere.

The decision comes down to two key questions:

Do You Need Iteration?

If you need to loop through entries, check the size, or list all keys/values, you must use Map or Set. WeakMap and WeakSet aren't iterable—they don't have forEach, keys(), values(), or a size property.

const cache = new Map();
cache.set('user1', {name: 'Alice'});
cache.forEach(user => console.log(user.name)); // ✓ Works

const metadata = new WeakMap();
metadata.set({id: 1}, 'data');
// metadata.forEach() ❌ Doesn't exist

Do You Want Automatic Cleanup?

If you're storing data about objects (metadata, caching, private properties) and want that data to disappear automatically when those objects are garbage collected, choose WeakMap or WeakSet.

// Strong: you must manually clean up
const userCache = new Map();
const user = {id: 1};
userCache.set(user, 'cached data');
// Even after user is gone elsewhere, cache keeps it alive

// Weak: automatic cleanup
const userMetadata = new WeakMap();
userMetadata.set(user, 'metadata');
// When user is no longer referenced, metadata disappears too

Use Map/Set when: You need iteration, size tracking, or complete control over lifecycle.

Use WeakMap/WeakSet when: You're associating data with objects temporarily and want memory-efficient automatic cleanup.

Key Takeaway: Choose strong collections (Map/Set) for data you actively manage and iterate; choose weak collections (WeakMap/WeakSet) for automatic memory management of object-associated metadata.