Array.from({length: 5}, (v, i) => i)


I was checking Array.from from this page:

However, I’m not quite clear what exactly “v” stands for in the code below.
My understanding is that (v, i) stands for (currentValue, index). Am I correct?
Or does it stand for something else?
If “v” is removed, then all element generated will become undefined.
How exactly does this “v” work in the function if it stands for currentValue?

Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

Thank you.

v is value, i is index. So that array.from() is basically building an empty array, then using that function to map() the members of that array. v is being ignored, we simply return the index (i) and set that as the value of the current array member.

Thank you for the explanation, but why “v” is required here? otherwise it will make an array of “undefined” element?
In the map() function below, we just need one argument instead (v, i) for example:

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = => x * 2);
// [2, 8, 18, 32]

In the code sample you show, you take the value (stored in the parameter x), and double it.

In the first code, the array.from(), you aren’t using the value, which is always the first parameter of a function passed to map (). You’re using the index position of the current member, which is always the second parameter.

You couldn’t simply do Array.from((length: 5}, (,i)=>I) (see the ,i in there, with no first parameter), so you have to create a throwaway placeholder for the value, that will never be referenced.

1 Like

Thank you very much for the explanation!
Now I am clear. :wink:

1 Like