Engineer Engineer - 4 months ago 13
Javascript Question

undefined values in Array(len) initializer

var a = Array(3);
var b = [undefined,undefined,undefined];


What's the reason, that
a.map
and
b.map
produce different results?

a.map(function(){ return 0; }); //produces -> [undefined,undefined,undefined]
b.map(function(){ return 0; }); //produces -> [0,0,0]

Answer

The array constructor creates an array with the given length. It does not create the keys. Array.prototype.map's callback function is only executed for the elements in the list.
That is, all values which are associated with a key (integer) 0 ≤ i < length.

  • Array(3) has zero keys, so .map's callback is never triggered.
  • [void 0, void 0, void 0] has three keys, for which the callback function is executed.

    Array(3).hasOwnProperty(0);                 // false
    [void 0, void 0, void 0].hasOwnProperty(0); // true
    

The specification and its polyfill are mentioned at MDN. At line 47, if (k in O) { shows that non-existant keys are not treated by the callback function.