creation

Array.from

Creates a new Array from an iterable or array-like object, optionally mapping each element as it is copied (ES2015). Reach for it to materialize a NodeList, Set, string, or `{length}` array-like into a real array.

Array.from(iterableOrArrayLike[, mapFn[, thisArg]])

Parameters

Parameter Purpose
iterableOrArrayLike Iterable (Set/Map/string) or array-like (has numeric `length`)
mapFn(element, index) Optional map function applied during construction (skips an intermediate array)
thisArg Value used as `this` inside mapFn

Examples

console.log(Array.from('abc'));

Logs: ['a', 'b', 'c']

console.log(Array.from(new Set([1,1,2,3])));

Logs: [1, 2, 3] (dedupe idiom)

console.log(Array.from({length: 3}, (_, i) => i * 2));

Logs: [0, 2, 4] (build range from array-like)

console.log(Array.from({length: 3}, () => []));

Logs: [[], [], []] (distinct references, unlike fill)

Gotcha

Array-like arguments need a numeric `length` property; plain objects without one become `[]`. Prefer `Array.from({length}, mapFn)` over `new Array(n).fill(...).map(...)` when you need distinct object slots.

Related methods

← All JS array methods · TypeScript vs JavaScript