Course contentsShow
← JavaScript
Lesson 841 of 2,72319. ArraysFree lesson

Array.from with Iterables

Use Array.from to create arrays from any iterable, including strings, sets, and maps.

Array.from with Iterables

You'll learn how to use Array.from() to convert any iterable object into a new array.

In the previous lesson, you learned that Array.from() can convert array-like objects (things with a length property and indexed elements) into arrays. But Array.from() has another superpower: it works with iterables too.

What Are Iterables?

An iterable is any object that can be looped over. You've already worked with several:

  • Strings (you can iterate over each character)
  • Sets (collections of unique values)
  • Maps (key-value pairs)

Think of iterables like containers that know how to hand out their contents one piece at a time, even if they don't store them as numbered positions like arrays do.

Converting Iterables to Arrays

Array.from() can take any iterable and create a proper array from it:

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

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

// From a Map
const userMap = new Map([['name', 'Alice'], ['age', 30]]);
const entries = Array.from(userMap);
console.log(entries); // [['name', 'Alice'], ['age', 30]]

This is incredibly useful when you need to use array methods on data that isn't originally in array form.

Key Takeaway: Array.from() converts any iterable (strings, Sets, Maps, etc.) into a real array, letting you use all array methods on data from different collection types.