JavaScript: Array.from

Wojciech Trawiński
JavaScript everyday
2 min readAug 27, 2018

The Array.from static method was introduced as a part of the ES6. It enables creating a new shallow-copied array from an array-like (object having a length property and indexed elements) or iterable object (Array, String, Map, Set). In this blog post, I will cover exemplary applications of the method.

Array-like object

In the following example, the object is considered as array-like due to presence of the length property and two indexed elements:

The number of elements in the resulting array equals to the value of the length property. Note that missing indexed elements get the undefined value, whereas non-indexed ones are neglected.

Arguments variable

Every regular JavaScript function (not an arrow function) has two additional, implicitly provided, variables in its lexical scope, namely the this and the arguments. The latter one is an example of an array-like object, therefore you need to convert it to an Array instance if you want to access a bunch of useful methods via its prototype:

Alternatively, you can make use of the much more powerful rest parameter.

Creating array

If you want to create an array of a given length, you can make use of the Array function in tandem with the map method in order to fill it with elements:

Note that the initial array of empty values has to be filled with some valid values to map over.

However, using the Array.from method, you can avoid creating intermediate arrays containing empty/undefined vales, since it’s initially filled with undefined vales and optionally accepts the mapping function as the second argument:

Iterable objects

Array

In the following example, a shallow copy of the source array gets created:

As an alternative, you can use the spread syntax to accomplish the goal.

String

The resulting array’s successive elements are the source string letters:

Note that the String.prototype.split method is more flexible, since it allows you to specify a custom delimiter other than the default empty string.

Map

The map entries become array’s items:

Set

Unique elements of the set become the resulting array’s elements:

Conclusions

With the aid of the Array.from method, you can create an Array instance based on an array-like or iterable object. The arguments variable within a regular function or an HTML collection are well-known examples of the former one. Instances of Array, String, Map and Set are JavaScript built-in iterable objects.

Live example:

I hope you liked the post and learned something new 👍. If so, please give me some applause 👏

--

--