Javascript array.from() method

Javascript array.from() method

Array.from() is one of the static methods that is present in the Javascript Array class. It is very important to understand the difference between the static methods and the prototype methods present in the Array class.

A static method is the one which can be called with a dot operator on that class name however the prototype methods can be called on the array instance.

Array.from() [Array is a Class , from is a constructor method on the Array class]

let arr = [1,2,3];

arr.map(value=>value*2);

Output //[2,4,6]

map() is a Prototype Method called on the instance 'arr' of an Array which iterates over every element of the array and multiples by 2.

To check the list of different constructor methods and prototype methods in the Array class we can do the following.

On the web console type console.dir(Array) and notice the result. We see that the below mentioned methods are some of the static methods present in the Array class.

from()
isArray()
of()

These methods could not be invoked on the instance of the Array.

let arr = []

arr.from("Javascript"); //This would throw an error

Array.from("Javascript") //This would work fine and return a new Array from the string provided in the input.

Please refer to my previous post click here on Array method to get a comprehensive list of the constructor methods and the prototype methods available in the Array class.

As per the official documentation "The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object."

Array-like objects are the ones which have a length property and contains a list of values.

Iterable Objects are the ones that implement the Symbol.iterator and they can be iterated using a for…of loop.