DEV Community

Cover image for How & When To Use JavaScript Array.from() Method
Wasim A Pinjari
Wasim A Pinjari

Posted on • Updated on • Originally published at wasimapinjari.netlify.app

How & When To Use JavaScript Array.from() Method

This is a quick demo explaining when & how to use JavaScript Array.from() method.

Suppose you want to write an array containing numbers from 1 to 100. It's probably a bad idea to write that manually.

This is a use case for using Array.from() method.

const array = Array.from({ length: 100}, (_, index) => index + 1);
console.log(array);
Enter fullscreen mode Exit fullscreen mode

We pass on two arguments:

In the first argument, we create an object mentioning the length of an array in key/value pair. This will create an empty array with 100 undefined items.

In the second argument, we pass an arrow function to map all the items in the created array to a new array that the Array.from() method going to return instead of the old array.

We're essentially passing an Array.map() method as the second argument since we're performing that action on an array containing 100 undefined items.

We keep the first parameter of Array.map() method blank using underscore, this is the item that the method is currently looping through.

In the second parameter, we receive the index of the currently looped item. We're using that index and adding one to it since the array start from index zero.

Let me illustrate what is happening a little better:

const array = [1, 2, 3];
const newArray = array.map((item, index) => item + index);
console.log(newArray)

// output: [1, 3, 5];
Enter fullscreen mode Exit fullscreen mode

Here we're performing the map method on an array.

What happens is we pass a function (also known as a callback function) in the map method as an argument, that function receives the first element of the array as the first argument which is 1 and its index as the second argument which is 0.

Then it proceeds to create a new array and push the value that it returns in that in each iteration. It keeps looping through all the array items and pushes whatever it returns to the new array and after the whole iteration is done it returns the new array.

For those who are confused, argument is the what we pass in a function and the parameter is the defined variable name for the argument.

Follow me: @wasimapinjari

Links: wasimapinjari.bio.link

Top comments (0)