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.

2
  • What do you understand var array = Array(5) to do? Commented Feb 1, 2017 at 22:17
  • You can also use Array.from() instead of Array() and .map() Commented Feb 1, 2017 at 22:28

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.