Spread Operator and the Iterator Protocol
What you'll learn: How the spread syntax secretly uses the iterator protocol to expand any iterable into individual values.
The Hidden Connection
You've used the spread operator (...) to expand arrays and other collections, but here's the magic behind it: spread syntax consumes iterators. When you write ...someValue, JavaScript checks if that value has a Symbol.iterator method. If it does, JavaScript calls that method to get an iterator, then repeatedly calls next() to extract each value until done becomes true.
This is why spread works with arrays, strings, Maps, and Sets—they all implement the iterator protocol!
How It Works Under the Hood
Think of spread as a fast-forward button for an iterator. Instead of manually calling next() over and over, spread does it automatically and places each value where you need it:
const letters = ['a', 'b', 'c'];
// Spread consumes the iterator
const expanded = [...letters]; // ['a', 'b', 'c']
// What's really happening (conceptually):
// 1. Get iterator: letters[Symbol.iterator]()
// 2. Call next() until done
// 3. Collect all values
Works with any iterable:
const text = 'hi';
const chars = [...text]; // ['h', 'i']
const nums = new Set([1, 2, 3]);
const arr = [...nums]; // [1, 2, 3]
If something doesn't have an iterator, spread fails:
const obj = { a: 1 };
// [...obj] ❌ TypeError: obj is not iterable
Key Takeaway: The spread operator is syntactic sugar for consuming an iterator—it automatically pulls every value from any iterable by using the iterator protocol behind the scenes.