Array.from(): build arrays from iterables (ES2015)
What you’ll learn
Section titled “What you’ll learn”- How
Array.from()chooses between the iterator protocol and an array-likelength. - How the optional mapper builds and transforms an array in one pass.
- The edge cases: holes, primitives, one-shot iterators, subclasses and the
parseInttrap. - When spread,
Array.of()orArray.fromAsync()is the better choice.
Summary
Section titled “Summary”TL;DR: Array.from(items, mapper?, thisArg?) returns a new, real Array from anything iterable (a Set, Map, string, generator) or array-like (an object with a length and indexed properties). If you pass a mapper, each element goes through it as it is copied.
It was added in ECMAScript 2015 and works in every current browser and runtime (see Compatibility).
The problem it solves
Section titled “The problem it solves”Before ES2015, APIs such as arguments and DOM NodeLists returned array-like objects without array methods. Converting them meant Array.prototype.slice.call(...), which reads awkwardly and does not handle iterables such as Set, Map or generators.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs). All outputs shown were produced with Node.js 22.23. The examples use an invented order-management app, OrdersPortal.
// An array-like object: numeric keys plus a length, but no array methods.const selectedRows = { 0: 'o-101', 1: 'o-102', 2: 'o-107', length: 3 };
// Before: borrow Array.prototype.slice.const before = Array.prototype.slice.call(selectedRows);
// After: Array.from works with array-likes and iterables alike.const after = Array.from(selectedRows);const fromSet = Array.from(new Set(['o-101', 'o-102', 'o-101']));
console.log(before, Array.isArray(before));console.log(after, Array.isArray(after));console.log(fromSet);Output:
[ 'o-101', 'o-102', 'o-107' ] true[ 'o-101', 'o-102', 'o-107' ] true[ 'o-101', 'o-102' ]How it works
Section titled “How it works”The algorithm (Array.from in the specification) has two paths:
- Iterable path. If
items[Symbol.iterator]exists, it iterates and appends each value. Strings iterate by code point,Maps yield[key, value]pairs. - Array-like path. Otherwise it converts
itemsto an object, readslength, and copies indexes0tolength - 1. Missing indexes are read asundefined.
The mapper is called as mapper(value, index) while copying, so no intermediate array is created. Unlike Array.prototype.map, it does not receive the array as a third argument.
// 1. Iterables use the iterator protocol.console.log(Array.from('héllo'));console.log(Array.from('a👍b')); // code points, not UTF-16 unitsconsole.log(Array.from(new Map([['o-1', 40], ['o-2', 15]])));
// 2. Array-likes use length and indexed reads; missing indexes become undefined.console.log(Array.from({ length: 3 }));console.log(Array.from({ length: 3, 1: 'b' }));
// 3. The mapper receives (value, index) only, and runs during the copy.console.log(Array.from({ length: 4 }, (_, i) => i * 10));console.log(Array.from(new Set([3, 1, 3]), (v, i) => `${i}:${v}`));
// 4. Holes in a sparse array become real undefined elements.const sparse = [1, , 3];console.log(Array.from(sparse), 1 in Array.from(sparse));
// 5. Primitives with neither an iterator nor a length give an empty array.console.log(Array.from(5), Array.from(true));
// 6. Errors.for (const bad of [() => Array.from(null), () => Array.from([1], 'not a function')]) { try { bad(); } catch (e) { console.log(e.constructor.name + ':', e.message); }}Output (error messages are V8’s wording):
[ 'h', 'é', 'l', 'l', 'o' ][ 'a', '👍', 'b' ][ [ 'o-1', 40 ], [ 'o-2', 15 ] ][ undefined, undefined, undefined ][ undefined, 'b', undefined ][ 0, 10, 20, 30 ][ '0:3', '1:1' ][ 1, undefined, 3 ] true[] []TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))TypeError: string "not a function" is not a functionCalled on a subclass, Array.from constructs that subclass. An iterator can only be consumed once.
class OrderList extends Array { total() { return this.reduce((sum, o) => sum + o.amount, 0); }}const list = OrderList.from([{ amount: 40 }, { amount: 15 }]);console.log(list instanceof OrderList, list.total());
function* ids() { yield 'o-1'; yield 'o-2'; }const it = ids();console.log(Array.from(it), Array.from(it));Output:
true 55[ 'o-1', 'o-2' ] []Realistic example
Section titled “Realistic example”An OrdersPortal list view needs page numbers, ID batches for a bulk API, distinct customers and a status summary. Each is one Array.from call.
const orders = [ { id: 'o-101', customer: 'c-7', status: 'paid' }, { id: 'o-102', customer: 'c-3', status: 'pending' }, { id: 'o-103', customer: 'c-7', status: 'paid' }, { id: 'o-104', customer: 'c-9', status: 'refunded' }, { id: 'o-105', customer: 'c-3', status: 'paid' },];
// Page numbers for a pager: 1..pageCount, with no intermediate array.const pageCount = Math.ceil(23 / 10);const pages = Array.from({ length: pageCount }, (_, i) => i + 1);
// Split IDs into batches of 2 for a bulk API that accepts at most 2 IDs per call.const chunk = (items, size) => Array.from({ length: Math.ceil(items.length / size) }, (_, i) => items.slice(i * size, i * size + size));const batches = chunk(orders.map((o) => o.id), 2);
// Distinct customers, in first-seen order.const customers = Array.from(new Set(orders.map((o) => o.customer)));
// Count by status: build a Map, then turn its entries into rows for a table.const counts = new Map();for (const { status } of orders) counts.set(status, (counts.get(status) ?? 0) + 1);const rows = Array.from(counts, ([status, count]) => ({ status, count }));
console.log(pages);console.log(batches);console.log(customers);console.log(rows);Output:
[ 1, 2, 3 ][ [ 'o-101', 'o-102' ], [ 'o-103', 'o-104' ], [ 'o-105' ] ][ 'c-7', 'c-3', 'c-9' ][ { status: 'paid', count: 3 }, { status: 'pending', count: 1 }, { status: 'refunded', count: 1 }]For asynchronous sources, such as an async generator over paginated results, Array.fromAsync() (ES2026) awaits each value and returns a promise. It runs on Node.js 22:
async function* fetchOrderPages() { for (let page = 1; page <= 3; page++) { await new Promise((r) => setTimeout(r, 5)); // stands in for a request yield `page ${page}`; }}console.log(await Array.fromAsync(fetchOrderPages()));console.log(await Array.fromAsync([Promise.resolve(1), 2], (v) => v * 2));Output:
[ 'page 1', 'page 2', 'page 3' ][ 2, 4 ]Common mistakes
Section titled “Common mistakes”-
Using
new Array(n).map()for a sequence.new Array(3)has holes, andmapskips holes, so you get[ <3 empty items> ]. UseArray.from({ length: n }, (_, i) => ...). -
Sharing one object across slots.
new Array(2).fill([])puts the same array in every slot. A mapper creates a fresh one per slot:Array.from({ length: 2 }, () => []). -
Passing
parseIntas the mapper. The mapper receives the index as its second argument, whichparseInttreats as a radix.console.log(Array.from(['10', '10', '10'], parseInt)); // [ 10, NaN, 2 ]console.log(Array.from(['10', '10', '10'], Number)); // [ 10, 10, 10 ] -
Reusing a consumed iterator. A generator or
map.entries()iterator is empty the second time. Convert once and keep the array. -
Expecting a deep copy.
Array.from(orders)copies references; the order objects are shared. -
Huge
lengthvalues.Array.from({ length: 1e9 })tries to allocate a billion elements; validate lengths from input.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Best tool |
|---|---|
| Iterable to array, no transformation | [...iterable] or Array.from(iterable) |
| Iterable to array and map each value | Array.from(iterable, fn) (one pass) |
Array-like without an iterator ({ length: 3, 0: 'a' }) |
Array.from (spread throws: not iterable) |
| Sequence or fixed-size array from a length | Array.from({ length: n }, fn) |
| Array from a list of arguments | Array.of() |
| Async iterable or array of promises | Array.fromAsync() (ES2026) |
| Copy an array to sort or reverse it | toSorted(), toReversed() |
If you only need to iterate once, skip the array: for...of reads the iterable without allocating.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, Array.from is supported in Chrome 45, Edge 12, Firefox 32, Safari 9, Node.js 4.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported it.
Array.fromAsync is newer: Chrome and Edge 121, Firefox 115, Safari 16.4, Node.js 22.0.0, Deno 1.38 and Bun 1.0. It became part of the standard in ECMAScript 2026.
TypeScript: Array.from is in lib.es2015.core.d.ts and lib.es2015.iterable.d.ts. TypeScript 6.0.3 types Array.fromAsync in lib.esnext.array.d.ts, so add esnext (or esnext.array) to lib to use it. TypeScript does not polyfill either method; use core-js for old runtimes.
Interview questions
Section titled “Interview questions”1. What is the difference between Array.from(x) and [...x]?
Spread only works on iterables and throws a TypeError for array-likes such as { length: 2 }. Array.from falls back to the length path, accepts a mapper so you avoid a second pass, and, when called on a subclass, returns an instance of that subclass.
2. Why does Array.from({ length: 3 }, (_, i) => i) work when new Array(3).map((_, i) => i) does not?
new Array(3) creates three holes, and map skips holes. Array.from reads each index (getting undefined) and calls the mapper for every one, so the result has real elements.
3. What does Array.from('a👍b') return, and why is it different from 'a👍b'.split('')?
['a', '👍', 'b'], because string iteration yields code points. split('') splits into UTF-16 code units and breaks the emoji into two surrogate halves. Neither handles multi-code-point graphemes such as flags; use Intl.Segmenter for those.
4. Senior scenario: a report endpoint streams 50,000 order rows through an async generator, and a teammate writes const rows = await Array.fromAsync(stream) before aggregating. What do you review?
fromAsync holds every row in memory and starts no work until the stream ends. For an aggregate such as totals per status, consume the stream with for await...of and update counters as rows arrive, keeping memory flat. Keep fromAsync for bounded sources where you need the whole array, and confirm target support (Node.js 22+, Safari 16.4+).
Key takeaways
Section titled “Key takeaways”Array.from(ES2015) builds a real array from any iterable or array-like.- The mapper runs during the copy and receives
(value, index). Array.from({ length: n }, fn)is the standard way to generate sequences and fresh objects per slot.- Prefer spread for plain iterables; use
Array.fromfor array-likes, mapping, or subclasses. - For async sources,
Array.fromAsync(ES2026) awaits each value.
Related pages
Section titled “Related pages”- Array.of: build an array from its arguments.
- Spread and rest operators: the shorter way to copy iterables.
- Iterators and iterables: the protocol
Array.fromuses first. - Map and Set: common sources for
Array.from. - Generators and Async iteration: sources for
Array.fromandArray.fromAsync. - Array.prototype.toSorted: copy and sort in one call.
- Arrays (basics)
Official references
Section titled “Official references”- ECMAScript Language Specification,
Array.from ( items [ , mapper [ , thisArg ] ] )(current draft; first published in ECMAScript 2015) - ECMAScript Language Specification,
Array.fromAsync - TC39 proposal: Array.fromAsync
- MDN: Array.from()
- MDN: Array.fromAsync()