How this code works?

Array.from({length: num+1}, (v, k) => k).slice(2);

I’m just curious how this code works specially the Array.from({length: num+1}.... part.

Array.from takes two arguments and creates an array.

  • the first is required, an array-like data structure. Arrays are just a special types of object with a length property, so if you do Array.from({length: 10}), you’re saying create an array from an object with a length of 10, so you’ll get an array of length 10 out of the other end.
  • the second (optional argument) is a mapping function: basically, it runs the function over every element in the array you’re creating and does something. It’s the same as the array method map, so have a read up on that if you’re not quite sure what it’s doing . v is the current value, and k is the current index, and the map is saying just return the index. So
Array.from({length: 5}, (v, i) => i)

Will create an array of length 5, and each value will be the index, so you get:


Edit: re arrays being objects:

[ , , , , ,]

Is basically the same as

{length: 5}



basically the same as

{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, length: 5}

If you put those objects into Array.from, you should see those arrays come out the other end