Spread vs Array.from
What you'll learn: You'll discover when to use the spread operator versus Array.from() for converting iterables to arrays, and why both exist.
Both the spread operator (...) and Array.from() can convert iterables into arrays, but they have subtle differences that matter in real code.
The Basic Difference
Spread requires placing the iterable inside array brackets:
const str = "hello";
const arr1 = [...str]; // ['h', 'e', 'l', 'l', 'o']
Array.from() is a method that takes the iterable as an argument:
const str = "hello";
const arr2 = Array.from(str); // ['h', 'e', 'l', 'l', 'o']
When They're Interchangeable
For simple conversions, they produce identical results:
const set = new Set([1, 2, 3]);
const withSpread = [...set]; // [1, 2, 3]
const withArrayFrom = Array.from(set); // [1, 2, 3]
Where Array.from() Shines
Array.from() accepts a mapping function as a second argument, like combining conversion with map():
const str = "123";
const numbers = Array.from(str, num => Number(num));
// [1, 2, 3]
// With spread, you'd need two steps:
const numbersSpread = [...str].map(num => Number(num));
Readability Considerations
Spread feels more concise for simple conversions, while Array.from() makes intent clearer with its explicit name and is more powerful when transformation is needed.
Key Takeaway: Use spread (...) for simple iterable-to-array conversions; reach for Array.from() when you need to transform elements during conversion or prefer explicit syntax.