Course contentsShow
← JavaScript
Lesson 1082 of 2,72325. Iterators and GeneratorsFree lesson

Destructuring and Iterables

Using array destructuring with any object that implements the iterator protocol.

Destructuring and Iterables

You'll learn how array destructuring works seamlessly with any iterable object, not just arrays.

The Core Idea

Array destructuring doesn't actually require an array—it requires an iterable. Since the destructuring syntax uses the iterator protocol under the hood, you can destructure strings, Maps, Sets, or any custom object that implements Symbol.iterator. JavaScript simply calls the iterator and assigns the yielded values to your variables in order.

Think of destructuring like unpacking boxes from a conveyor belt. It doesn't matter what's producing the boxes (array, string, Set)—as long as they come one at a time in order, destructuring can assign them to variables.

Destructuring Different Iterables

// Strings are iterable (character by character)
const [first, second] = "Hello";
console.log(first);  // "H"
console.log(second); // "e"

// Sets are iterable
const mySet = new Set([10, 20, 30]);
const [a, b, c] = mySet;
console.log(a); // 10
console.log(b); // 20

// Maps are iterable (yields [key, value] pairs)
const myMap = new Map([['x', 1], ['y', 2]]);
const [firstPair, secondPair] = myMap;
console.log(firstPair);  // ["x", 1]
console.log(secondPair); // ["y", 2]

// You can even destructure the pairs further
const [[key1, val1], [key2, val2]] = myMap;
console.log(key1, val1); // "x" 1

This works because each of these types implements Symbol.iterator, making them compatible with the destructuring syntax.

Key Takeaway: Array destructuring works with any iterable, not just arrays—it relies on the iterator protocol to sequentially assign values to variables.