Course contentsShow
← JavaScript
Lesson 965 of 2,72322. Spread and RestFree lesson

Spreading Iterables into Arrays

Use spread with any iterable like Sets, Maps, or custom iterators to create arrays.

Spreading Iterables into Arrays

What you'll learn: You'll discover how the spread operator works with any iterable—not just arrays and strings—to seamlessly create arrays from Sets, Maps, and custom iterators.

The Core Idea

The spread operator (...) doesn't just work with arrays and strings. JavaScript treats any iterable the same way. This means you can spread Sets, Map keys/values, and even custom iterables directly into array literals. The spread operator internally calls the iterable's iterator and collects all its values into your new array.

Think of the spread operator as a universal translator: it speaks the language of any iterable and converts whatever it finds into array elements.

Spreading Sets

Sets are iterables, so you can spread them into arrays to eliminate duplicates or convert them for array operations:

const uniqueNumbers = new Set([1, 2, 2, 3, 4, 4]);
const array = [...uniqueNumbers];
console.log(array); // [1, 2, 3, 4]

Spreading Map Keys and Values

Maps are iterables that yield [key, value] pairs. You can spread the Map itself or use .keys() and .values():

const scores = new Map([['Alice', 95], ['Bob', 87]]);
const pairs = [...scores];        // [['Alice', 95], ['Bob', 87]]
const names = [...scores.keys()]; // ['Alice', 'Bob']
const values = [...scores.values()]; // [95, 87]

Why This Matters

Many JavaScript features return iterables (like querySelectorAll in the browser returns a NodeList). Spreading them into arrays lets you use array methods immediately instead of converting manually.

Key Takeaway: The spread operator works with any iterable—Sets, Maps, or custom iterators—making it a powerful, universal tool for creating arrays from diverse data sources.