Array.from()
A static on Array, not a method on an array. Its two superpowers: it handles array-LIKE objects that spread cannot, and its second argument maps as it builds.
Demo
A string is iterable, so it expands to one element per character — the same as spreading it. What the demo cannot show is the case that makes Array.from genuinely necessary: array-LIKE objects such as a DOM NodeList or the old arguments object have a length but no iterator, and a spread cannot handle them while Array.from can.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| source | iterable | array-like | yes | Anything iterable, or any object with a numeric length property. A plain object without length yields an empty array. |
| mapFn | Function | no (none) | Called as mapFn(element, index) while building. Avoids the intermediate array that Array.from(x).map(f) would create. |
| thisArg | any | no (undefined) | Value of `this` inside mapFn. |
Return value
Array — A new real array. Accepts anything iterable (Set, Map, string, generator) and anything array-like (an object with a length).
Common patterns
const els = Array.from(document.querySelectorAll("li")); const unique = Array.from(new Set(values));
const range = Array.from({length: 5}, (_, i) => i);
const grid = Array.from({length: 3}, () => new Array(3).fill(0));
Examples
Pitfalls
Array.from({a: 1})
Object.values({a: 1})
new Array(3).map((_, i) => i)
Array.from({length: 3}, (_, i) => i)
[1, 2].from()
Array.from([1, 2])
Array.from(set).map(f)
Array.from(set, f)
When to use
- Converting a NodeList, Set, Map or arguments object to a real array
- Array-like objects that a spread cannot handle
- Building a range or a grid with a per-element factory
- Mapping while converting, in a single pass
- The source is already an iterable and you want the shortest form → [...source]
- You want the same value in every slot → fill, though watch the shared reference
- The source is a plain object → Object.values or Object.entries
Notes
FAQ
Spread is shorter for anything iterable. Array.from is required for array-LIKE objects that have a length but no iterator — older DOM collections and the arguments object — and it is better when you also want to map, since the second argument avoids an intermediate array.
Array.from(nodeList); // works [...nodeList]; // only if iterable