Destructuring with Iterables
What you'll learn: Array destructuring isn't limited to arrays—it works with any iterable object in JavaScript.
The Core Idea
You've seen array destructuring work with actual arrays, but here's the powerful truth: JavaScript's destructuring syntax works with any iterable, not just arrays. An iterable is any object that implements the iteration protocol—meaning it can be looped over. This includes arrays, strings (which you've already destructured), Sets, Maps, and even custom iterables.
Think of destructuring as a pattern-matching tool that asks: "Can I loop through this to pull out values one by one?" If the answer is yes, destructuring works.
Destructuring Sets
const uniqueNumbers = new Set([10, 20, 30, 40]);
const [first, second] = uniqueNumbers;
console.log(first); // 10
console.log(second); // 20
Even though a Set isn't an array, destructuring extracts values in iteration order.
Destructuring Map Entries
const userMap = new Map([
['name', 'Alice'],
['age', 30]
]);
const [firstEntry, secondEntry] = userMap;
console.log(firstEntry); // ['name', 'Alice']
console.log(secondEntry); // ['age', 30]
Maps are iterables that yield [key, value] pairs, and destructuring captures them sequentially.
Why This Matters
Understanding that destructuring operates on iterables rather than just arrays opens up powerful patterns. You can destructure any data structure that follows the iteration protocol, making your code more flexible and expressive.
Key Takeaway: Array destructuring syntax works with any iterable object—arrays, strings, Sets, Maps, or custom iterables—because it relies on the iteration protocol, not array-specific behavior.