Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

Array.from()

Reference for JavaScript Array.from(): create arrays from iterables, strings, Sets, Maps and array-like objects, with an optional mapping function.

Array.from() is a static method that creates a new, shallow-copied array from an iterable (a string, Set, Map, generator and so on) or from an array-like object (an object with a length and indexed properties, such as arguments or a NodeList).

It takes an optional mapping function as a second argument, which makes it a handy way to generate arrays of a given length: Array.from({ length: 5 }, (_, i) => i).

JavaScript
Array.from("abc"); // ["a", "b", "c"]

Try it

JS From iterables and array-likes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Mapping and generating

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Array.from(items)
Array.from(items, mapFn)
Array.from(items, mapFn, thisArg)
Name Description
items An iterable or array-like object to convert.
mapFn Optional. Called for each element as mapFn(element, index); its return value is stored instead.
thisArg Optional. Value used as this inside mapFn (not useful with arrow functions).

Return value: a new Array instance.

Exceptions: a TypeError if items is null or undefined, or if mapFn is given but is not a function.

Usage notes

  • Iterables win. If the object has Symbol.iterator, it is iterated; otherwise length and numeric indexes are read. Strings are iterated by code point, so "๐Ÿ˜€" is one element.
  • Missing indexes become undefined. Array.from({ length: 3 }) gives [undefined, undefined, undefined] with real elements, not holes, so map() works on the result.
  • Maps give entries, Set gives values. Use .keys(), .values() or .entries() to pick another view.
  • Shallow copy. Nested objects are shared with the source, as the Array(2).fill([]) comparison reminds you: use a mapping function to create a distinct object per element.
  • Mapping is built in. Array.from(x, fn) avoids the temporary array that Array.from(x).map(fn) creates.
  • Spread alternative: [...iterable] is shorter for iterables, but it does not accept array-likes and has no mapping function.
  • Subclasses: called on a subclass (MyArray.from(...)), it creates an instance of that subclass.
  • Async iterables are not supported; use Array.fromAsync() where available.

Browser support

Array.from() is supported in every current browser. Array.fromAsync() is newer, so check a compatibility table before using it.