Let's see the signature of Array.from() method first.
Array.from(arrayLike, mapFn)
So, the first argument should be an arrayLike object (an object that has a length property of a non-negative integer). You can pass an array, string, etc. as well.
The second parameter is a map function which maps the the elements of the first argument (arrayLike) to the returned value from the callback function.
This map function takes a callback function with following signature.
callback(value, index)
The map function creates a new array populated with the results of calling the callback function (v, i) => i
on every element in first argument of Array.from
.
Now, let's see first case,
let test1 = Array.from(5, (v,i) => i);
Here, (v, i) => i
is a map function. v
is element of arrayLike object and i
is the index of that element. The index i
is returned.
But, 5
is neither an array nor an arrayLike object and the length property of 5
is undefined
. So, map function maps no (zero) element and produces an empty array. Think of the following implementation.
function mapFn (arrayLike, callback) {
let result = [];
for (let i = 0; i < arrayLike.length; i++) {
let mappedValue = callback(arrayLike[i], i);
result.push(mappedValue);
}
return result;
}
If you pass 5
to the mapFn function, the for
loop iterates 0
times and mapFn
returns an empty array.
In case of second example,
let test2 = Array.from({length:5}, (v,i) => i); // [0,1,2,3,4]
{length: 5}
is an arrayLike object. The map function produces an array with returned values of the callback function. The callback function returns index. Hence, [0,1,2,3,4]
.
In the callback function only the i
parameter is used and returned from the function. v
argument is not used. But, it needs to be there so that the second parameter i
can be accessed. So, (_, i)
is same as (v, i)
. You can name the parameters with any valid variable name.