Sub topic 16
Making Arrays from Iterables and Array-Likes
A lot of the data you handle in JavaScript looks like a list but isn't an array. A Set of unique IDs, the entries of a Map, the characters of a string, the arguments object, and a DOM NodeList all hold ordered values. Most of them lack map, filter, and reduce. This chapter shows how to turn them into real arrays with Array.from, when spread syntax does the same job, and why Array.of exists.
This chapter assumes you already know callbacks and the (element, index, array) signature, plus spread syntax. Both were covered earlier in this tutorial.
Two kinds of "list-like" values
JavaScript has two separate ways for a value to act like a list.
- An iterable is an object with a
Symbol.iteratormethod.for...ofand spread syntax use that method to step through the values. Arrays, strings,Set,Map, typed arrays, generator objects, andNodeListare all iterable. - An array-like is an object with a numeric
lengthproperty and values stored under the keys0,1,2, and so on. It doesn't need an iterator.{ 0: 'a', 1: 'b', length: 2 }is array-like. Theargumentsobject andHTMLCollectionare both array-like.
A value can be both, one, or neither. Array.from accepts both kinds, and that is the main reason to choose it over spread.
Converting iterables
When you give Array.from an iterable, it collects whatever the iterator yields.
const ids = new Set([3, 1, 3, 2, 1]);
console.log(Array.from(ids)); // [3, 1, 2]
const prices = new Map([['tea', 3], ['cake', 5]]);
console.log(Array.from(prices)); // [['tea', 3], ['cake', 5]]
console.log(Array.from(prices.keys())); // ['tea', 'cake']
console.log(Array.from(prices.values())); // [3, 5]
function* range(start, end) {
for (let i = start; i < end; i++) yield i;
}
console.log(Array.from(range(2, 6))); // [2, 3, 4, 5]Converting a Set back to an array is the usual one-liner for removing duplicates: Array.from(new Set(list)). The result keeps the order in which each value first appeared.
Strings split by code point
Array.from('text') iterates the string. String iteration walks Unicode code points, while split('') cuts the string into UTF-16 code units. The two give different results for characters outside the Basic Multilingual Plane, such as most emoji.
const s = 'a😀b';
console.log(s.split('').length); // 4 (the emoji becomes two broken halves)
console.log(Array.from(s).length); // 3
console.log(Array.from(s)); // ['a', '😀', 'b']Iterators are used up
Generator objects and the iterators returned by map.keys() and similar methods can be read only once. If you convert one twice, the second result is empty.
const it = new Set([1, 2]).values();
console.log(Array.from(it)); // [1, 2]
console.log(Array.from(it)); // []If you need the values more than once, convert once and reuse the array.
Converting array-likes
When the input has no iterator, Array.from reads length and copies each index from 0 to length - 1. Indexes that are missing come out as undefined.
const arrayLike = { 0: 'a', 2: 'c', length: 3 };
console.log(Array.from(arrayLike)); // ['a', undefined, 'c']
function legacy() {
return Array.from(arguments).map(x => x * 2);
}
console.log(legacy(1, 2, 3)); // [2, 4, 6]New code should use rest parameters (function f(...args)), which give you a real array directly. You still run into arguments in older code.
The length value goes through some conversions that can catch you out:
console.log(Array.from({ length: 2.9 })); // [undefined, undefined] (truncated)
console.log(Array.from({ length: -5 })); // [] (clamped to 0)
console.log(Array.from({ length: '3' })); // [undefined, undefined, undefined]
console.log(Array.from(42)); // [] (no iterator, no length)
try {
Array.from(null);
} catch (err) {
console.log(err instanceof TypeError); // true
}In a browser, document.querySelectorAll returns a NodeList, which is iterable and has a forEach method but no map or filter. getElementsByClassName returns an HTMLCollection, which is iterable in modern browsers but has neither. Converting either one gives you the full array API:
// Run in a browser console on any page
const linkTexts = Array.from(document.querySelectorAll('a'), a => a.textContent.trim());
console.log(linkTexts);The mapping function
Array.from takes an optional second argument, a mapping function, and an optional third argument that sets this inside it. The mapping function receives only (value, index). Unlike Array.prototype.map, it gets no third array argument, because the array is still being built.
const squares = Array.from({ length: 5 }, (_, i) => i * i);
console.log(squares); // [0, 1, 4, 9, 16]
const upper = Array.from(new Set(['x', 'y']), (ch, i) => `${i}:${ch.toUpperCase()}`);
console.log(upper); // ['0:X', '1:Y']Array.from(src, fn) gives the same result as Array.from(src).map(fn) without building an intermediate array. The difference matters for large inputs. The two also behave differently with sparse arrays: Array.from turns holes into undefined before calling fn, while .map skips holes.
Building filled arrays safely
Array.from({ length: n }, factory) is the standard way to create n independent values. Compare it with fill, which puts the same reference into every slot:
const shared = Array(3).fill([]);
shared[0].push('oops');
console.log(shared); // [['oops'], ['oops'], ['oops']]
const separate = Array.from({ length: 3 }, () => []);
separate[0].push('ok');
console.log(separate); // [['ok'], [], []]Array(3) creates three empty slots (holes). Array.from({ length: 3 }) creates three real undefined values, so forEach and map visit every one of them.
Array.of and the constructor trap
The Array constructor treats a single number argument as a length:
console.log(Array(3)); // [ <3 empty items> ]
console.log(Array(3, 4)); // [3, 4]
console.log(Array('3')); // ['3']
console.log(Array.of(3)); // [3]
console.log(Array.of(3, 4)); // [3, 4]
// Array(-1) and Array(1.5) throw RangeError: Invalid array lengthArray.of always treats its arguments as elements. In everyday code an array literal [3] is clearer. Array.of is useful when you need a function value, for example values.map(Array.of). That expression wraps each value, but map passes the index and the array too, so [1, 2].map(Array.of) gives [[1, 0, [1, 2]], [2, 1, [1, 2]]]. Use values.map(v => [v]) when you mean "wrap each value".
Spread vs Array.from vs Array.of
| Tool | Accepts iterables | Accepts array-likes | Built-in mapping | Typical use |
|---|---|---|---|---|
| `[...x]` | Yes | No (TypeError) | No | Copy or convert an iterable inline, merge several sources |
| `Array.from(x, fn)` | Yes | Yes | Yes, `(value, index)` | Array-likes, generated sequences, convert and map in one pass |
| `Array.of(...items)` | n/a | n/a | No | Build an array from arguments without the length trap |
const arrayLike = { 0: 'a', length: 1 };
try {
console.log([...arrayLike]);
} catch (err) {
console.log(err.message); // e.g. "arrayLike is not iterable"
}
console.log(Array.from(arrayLike)); // ['a']Use spread when you know the source is iterable and you are combining values, as in [...setA, ...setB]. Use Array.from when the input might be a plain array-like or when you want to map during the conversion. Both make shallow copies, so nested objects are shared with the source.
Async sources: Array.fromAsync
ES2024 added Array.fromAsync, which collects async iterables, or sync iterables of promises, into an array and returns a promise. It is available in Node.js 22 and current browsers.
async function* fetchPages() {
for (let page = 1; page <= 3; page++) {
await new Promise(r => setTimeout(r, 10));
yield `page ${page}`;
}
}
async function main() {
const pages = await Array.fromAsync(fetchPages());
console.log(pages); // ['page 1', 'page 2', 'page 3']
}
main();Array.fromAsync awaits each value in turn, one after another. If you already have an array of independent promises and want them to run concurrently, Promise.all is still the right tool.
Exercise
Write one expression that turns the string 'banana' into an array of its unique letters in order of first appearance, uppercased: ['B', 'A', 'N'].
Show answer
Array.from(new Set('banana'), ch => ch.toUpperCase()). The Set iterates the string's characters and keeps only first occurrences ('b', 'a', 'n'). Array.from then maps each one to uppercase in a single pass.
Exercise
What does Array.from({ length: 3, 1: 'x' }, (v, i) => v ?? i) return, and why would [...{ length: 3, 1: 'x' }] behave differently?
Show answer
It returns [0, 'x', 2]. The object has no iterator, so Array.from reads length 3. Indexes 0 and 2 are missing and arrive as undefined, which the ?? operator replaces with the index. Spread needs Symbol.iterator, and a plain object doesn't have one, so the spread version throws a TypeError.
Exercise
A teammate writes const grid = Array(3).fill(Array(3).fill(0)); and then sets grid[0][0] = 1. What goes wrong, and how do you fix it?
Show answer
The outer fill puts the same inner array into all three rows, so grid[0][0] = 1 changes every row's first cell. Create each row separately: Array.from({ length: 3 }, () => Array(3).fill(0)). Filling with the number 0 is safe because numbers are primitives.