When to Use Array.from vs Spread
You'll learn when to reach for Array.from() versus the spread operator (...) for converting iterables to arrays.
Both Array.from() and the spread operator can convert iterables (like strings, sets, or maps) into arrays, but they have different strengths. Understanding when to use each makes your code clearer and more efficient.
Basic Overlap
For simple iterable-to-array conversions, both work identically:
const str = "hi";
Array.from(str); // ['h', 'i']
[...str]; // ['h', 'i']
When to Prefer Array.from
Use Array.from() when you need transformation during conversion. Its optional mapping function lets you transform elements as you create the array:
const nums = "123";
Array.from(nums, x => Number(x) * 2); // [2, 4, 6]
// With spread, you'd need a separate step:
[...nums].map(x => Number(x) * 2); // [2, 4, 6]
Use Array.from() for array-like objects (objects with a length property and indexed elements, but no iterator):
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
Array.from(arrayLike); // ['a', 'b']
// [...arrayLike]; // Error: not iterable
Use Array.from() for generating sequences (with the mapping function):
Array.from({ length: 3 }, (_, i) => i * 10); // [0, 10, 20]
When to Prefer Spread
Use spread for simple conversions when you don't need transformation — it's shorter and more readable:
const set = new Set([1, 2, 3]);
[...set]; // Cleaner than Array.from(set)
Use spread when combining with other array elements:
const arr = [1, 2];
[0, ...arr, 3]; // [0, 1, 2, 3]
Key Takeaway: Use Array.from() when you need transformation or handle array-like objects; use spread (...) for simple, clean conversions of iterables.