ReviseAlgo Logo

Arrays & Iterables

Maps & WeakMaps

Master ES6 Maps and WeakMaps. Learn key differences compared to standard objects, support for non-string keys, and garbage collection mechanisms in WeakMaps.

Last Updated: July 15, 2026 10 min read

1. Introduction

Standard objects only support strings or symbols as keys. ES6 introduced Maps (supporting keys of any data type, including objects) and WeakMaps (keys are objects only, with weak garbage collection references) to manage key-value pairs cleanly.

2. Why It Matters

Using standard objects to map metadata to object instances can mutate the objects or prevent them from being garbage collected. Maps and WeakMaps solve this issue by storing associations externally without mutating the object instances themselves.

3. Real-World Analogy

Think of a Coat Check Room:

  • Standard Object (Sticker labeling): Sticking a paper label directly onto a guest's coat. You write "Owner: Alice" directly on the garment (mutating the object instance).
  • Map (Standard Coat Check): You hand the guest a plastic token (key) and hang their coat on a matching numbered hook (value) on the rack. The coat is associated with the token externally without changing the coat itself. The hook remains reserved until the guest returns the token.
  • WeakMap (Disposable Tag Check): Using a barcode tag that dissolves if the coat is discarded. If the guest throws their coat in the trash (removes all references to the object), the tag is automatically invalidated, and the hook is cleared from the registry (garbage collection) automatically.

4. Maps

A Map is an ordered collection of key-value pairs where keys can be of any data type.

5. WeakMaps

A WeakMap is a collection of key-value pairs where keys must be objects only. It has three key characteristics:
Object keys only: Values can be any data type, but keys must be objects.
Weak references: Keys are referenced weakly. If a key object has no other references pointing to it, it is garbage collected, and its value is removed from the WeakMap automatically.
Not iterable: WeakMaps do not expose methods like size, keys, or loops.

6. Comparison Summary

Feature Map WeakMap
Allowed Key Types Primitives & Objects Objects only
Key Reference Strength Strong (prevents garbage collection) Weak (allows garbage collection)
Iterability Iterable (forEach, keys, size) Not iterable (no size property)

7. Practical Example

This script demonstrates using a Map as a clean registry cache:

8. Common Mistakes

  • Trying to store primitives as keys in a WeakMap: Attempting to call weakmap.set('stringKey', 'value') throws a TypeError.
  • Using standard object literals as caches for object instances: Doing this converts the key object references to strings (e.g. "[object Object]"), which conflicts and overwrites data. Use a Map or WeakMap instead.

9. Quick Quiz

Q1: What happens if an object key stored in a WeakMap has no other active references pointing to it?

A) It remains in the WeakMap until clear() is called

B) It is garbage collected and removed from the WeakMap automatically

Answer: B — WeakMap keys are referenced weakly. If the key object has no other active references, it is garbage collected and its entry is automatically removed from the WeakMap.

10. Scenario-Based Challenge

The Private Counter Cache:

You want to attach private metadata to a class instance without declaring it as a public property or modifying the class definition. Design a private cache helper using a WeakMap where the class instance acts as the key.

11. Debugging Exercise

Explain why this lookup returns undefined, and how to fix it:

const userPermissions = new Map();

userPermissions.set({ id: 101 }, ['read', 'write']);

// Verify access permissions console.log(userPermissions.get({ id: 101 })); // logs undefined! Why?

View Solution

Diagnosis: Maps compare objects by reference, not value. The object passed to get() is a new object literal with a different memory reference than the one used as the key in set().

Fix: Store the key object reference in a variable, and use that variable for both set() and get() operations:

const userKey = { id: 101 };
userPermissions.set(userKey, ['read', 'write']);
console.log(userPermissions.get(userKey)); // ['read', 'write']

12. Interview Questions

🟢 Q1: Compare standard objects and Map objects in terms of keys and performance.

Answer:
Keys: Standard objects only support strings or symbols as keys. Maps support keys of any data type, including objects, functions, or primitives.
Ordering: Objects do not guarantee property order. Maps guarantee key insertion order during iteration.
Performance: Maps are optimized for scenarios involving frequent additions and removals of key-value pairs.

13. Production Considerations

  • Memory Management: Use WeakMap when mapping metadata to objects that are dynamically created and destroyed (like DOM elements or API nodes). This allows the objects to be garbage collected automatically when they are no longer needed, preventing memory leaks.