1

I was looking at this answer and I've stumbled upon the need of Array.apply to fill array:

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

I've checked and this won't actually work:

var array = Array(5).map(function() { return 0; });

I know i could do

var array = Array(5).fill(0);

to obtain same result as the first method, I'm just wondering why it needs Array.apply with null as parameter.

Community
  • 1
  • 1
nicecatch
  • 1,687
  • 2
  • 21
  • 38

1 Answers1

3

Apply.apply(thisArg, [argsArray]) have two Parameters

thisArg

The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.

argsArray

An array-like object, specifying the arguments with which fun should be called, or null or undefined if no arguments should be provided to the function.

For details visit

Muhammad Saqlain
  • 2,112
  • 4
  • 33
  • 48
  • I think (at least, I thought) what apply does, I just can't figure out what it does in this context. Boxing Array(5) (that is just an empty array of length 5) transforms it in 5 'undefined' parameters, right? – nicecatch Feb 03 '17 at 16:26