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

Why WeakMap/WeakSet Aren't Iterable

Understanding the fundamental impossibility of iteration due to garbage collection timing.

Why WeakMap/WeakSet Aren't Iterable

You'll learn why JavaScript fundamentally can't let you loop over WeakMaps or WeakSets.

The Core Problem

Remember that WeakMaps and WeakSets hold weak references to their keys/values, meaning JavaScript's garbage collector can remove entries at any time when nothing else references them. This creates an impossible situation for iteration.

The Timing Paradox

Imagine you start looping over a WeakMap's entries. Between when you begin the loop and when you reach the next entry, the garbage collector might run and remove some keys from the collection. Your loop would become unpredictable—sometimes an entry exists, sometimes it's suddenly gone mid-iteration.

Think of it like counting people in a room where some might vanish without warning. You could never give an accurate count because by the time you finish, the number might have changed. The list becomes unreliable the moment you try to read it.

Why This Matters

Unlike regular Maps and Sets where JavaScript guarantees entries stay put until you explicitly remove them, WeakMaps and WeakSets make no such promise. The garbage collector operates independently of your code, potentially at any moment. There's no way to "freeze" the collection's state long enough for a reliable iteration.

This is by design—enabling iteration would require keeping strong references to all keys temporarily, which defeats the entire memory management purpose of weak collections.

Key Takeaway: WeakMaps and WeakSets can't be iterated because garbage collection can remove entries unpredictably at any time, making any iteration inherently unreliable and defeating their memory management benefits.