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

Array.from with Iterables

Converting any iterable into an array using Array.from.

Array.from with Iterables

You'll learn how to transform any iterable (arrays, strings, maps, sets, etc.) into a fresh array using Array.from().

What You're Doing

Array.from() is a built-in method that accepts any iterable and converts it into a new array. Since you've learned that iterables follow the iterator protocol (they have Symbol.iterator), Array.from() works seamlessly with strings, Maps, Sets, arrays, and even custom iterables—basically anything you can loop over with for...of.

Think of Array.from() as a universal translator: it doesn't care what kind of iterable you hand it, it just asks "Can I iterate over you?" and if the answer is yes, it collects each value into a plain array.

How It Works

// From a string (iterable)
const letters = Array.from('hello');
console.log(letters); // ['h', 'e', 'l', 'l', 'o']

// From a Set (iterable)
const mySet = new Set([1, 2, 3, 2, 1]);
const arr = Array.from(mySet);
console.log(arr); // [1, 2, 3]

// From a Map's keys (iterable)
const myMap = new Map([['a', 1], ['b', 2]]);
const keys = Array.from(myMap.keys());
console.log(keys); // ['a', 'b']

Unlike the spread operator ([...iterable]), Array.from() explicitly signals your intent to create an array and works consistently across all iterable sources.

Why Use Array.from?

When you need array methods like .map(), .filter(), or .slice() but your data is in a Set, Map, or string format, Array.from() is your bridge. It converts the iterable into an array you can manipulate with all the standard array tools you already know.

Key Takeaway: Array.from() converts any iterable into a new array, giving you a universal way to work with array methods regardless of the original data structure.