0

I'm generally curious why the first example doesn't populate array with default values?

// first example
var arr = new Array(5);
var r = arr.map(function () { return 0; });
console.log(r); // []

// second example
var arr2 = Array.apply(null, Array(5));
var r2 = arr2.map(function () { return 0; });
console.log(r2); // [0, 0, 0, 0, 0]
2
  • 2
    Because there's nothing in the first array except empty slots and map can't work on those. The second is an array of undefined elements which it can process. Commented Apr 2, 2016 at 16:35
  • 1
    This is valid for all programming language, when you instantiate array, it create empty slots with no values. Commented Apr 2, 2016 at 16:48

1 Answer 1

1

This is what I found on the MDN article about Array.protoype.map.

It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

Array elements will not be set when you initialize an array with Array constructor.

A better approach for new Array(5) would be Array.from({length: 5}), which works fine with map.

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

Comments

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.