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);
// output: (100) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
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];
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: Wasim A Pinjari