0
var hello = Array.apply(null, Array(5)).map(function (x, i) { return i; });

I get what map does, but I don't understand why the function does what it does to make the hello == [0, 1, 2, 3, 4]

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
  • 1
    It is keys of the array of length 5. What makes you confused? – Vladimir G. May 25 '17 at 08:59
  • `Array.apply(null, Array(5))` returns an array of size full of `undefined`s. Whatever there is inside, this `map` function ignores values and converts it into array [0, 1, 2, 3, 4] because second argument of `map` is index. – Yeldar Kurmangaliyev May 25 '17 at 09:00
  • Also have a look at https://stackoverflow.com/questions/22949976/why-does-array-applynull-args-act-inconsistently-when-dealing-with-sparse-a – Jonas Wilms May 25 '17 at 09:01

3 Answers3

0

The second parameter on the closure passed to map is the array key. That is what is being returned so you're getting 5 array keys, starting at 0.

Jim Wright
  • 5,905
  • 1
  • 15
  • 34
0

Maybe we should break it down:

var arr = Array(5);
arr === [,,,,,];  // array with five undefined slots
arr === [undefined, undefined, undefined, undefined, undefined]; // same as this :)

Each has an index:

arr[4]; // yay! => undefined

map loops through each slot and the mapping function gets 2 params, the value and the index.

function (x, i) { return i; }

map produces an array of all the return values from the mapping function.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
0

You can find out by performing a dry run of your code:

var hello = Array.apply(null, Array(5))

At this point:

hello == [undefined,undefined,undefined,undefined,undefined]

Now:

hello.map(function (x, i) { return i; });

Is the equivalent to (use the comments to see how the below references the above function:

for(var i = 0; i < hello.length; i++){ // i is the index
    x = hello[i];                      // x is the value at each index

    // Function body below using `hello[i] = ` instead of return
    hello[i] = i;
}

Hence the result from setting each element in the list to the index of that element:

[0, 1, 2, 3, 4]
Nick is tired
  • 6,860
  • 20
  • 39
  • 51