SyntaxStudy
Sign Up
JavaScript Intermediate 7 min read

Array.from() and Array.of()

Array.from() and Array.of()

In addition to array literals, JavaScript provides two static constructor methods for creating arrays from other data sources or from a fixed list of arguments.

Array.from(iterable, mapFn)

Array.from converts any iterable or array-like object into a real array. Array-like objects have numeric indices and a length property but lack array methods — NodeList, arguments, Map, Set, and strings all qualify. An optional second argument works like a map function applied to each element during conversion.

Array.of(...items)

Array.of creates an array from its arguments. Unlike the Array(n) constructor — which creates a sparse array of length n when called with a single number — Array.of(7) creates [7], making its behaviour consistent and predictable.

Creating Ranges

Array.from({ length: n }, (_, i) => i) is the idiomatic way to create a range array without a loop.

Example
console.log(Array.from('hello')); // ['h','e','l','l','o']
console.log(Array.from(new Set([1, 2, 2, 3]))); // [1,2,3]
console.log(Array.from({length: 5}, (_, i) => i)); // [0,1,2,3,4]
console.log(Array.from({length: 5}, (_, i) => i + 1)); // [1,2,3,4,5]
console.log(Array.of(1, 2, 3));   // [1,2,3]
console.log(Array.of(7));         // [7]
console.log(Array(7));            // [,,,,,,] sparse!
console.log(Array.from(new Map([['a', 1], ['b', 2]]))); // [['a',1],['b',2]]
Pro Tip

Use Array.from(nodeList) to convert a DOM NodeList to a real array before calling array methods on it — NodeList does not have map, filter, or reduce.