Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript mapping of new Array() [duplicate]

new Array(3)returns an array of length 3 containing 3 undefineds which is equivalent to [undefined, undefined, undefined];

However,

[undefined, undefined, undefined].map((val, i) => i) produces the expected result of [0, 1, 2]. But new Array(3).map((val, i) => i) produces [undefined, undefined, undefined], as if the map function had not effect whatsoever.

Could anyone explain why?

EDIT Looks like there is a flaw in my understanding of new Array(). It does NOT create a new array. It creates an object with key length equal to the argument passed in. Thanks for the answers and comments.

Btw if you do need an array like [undefined, undefined, undefined] to iterate/map over, or for anything then [...new Array(m)] should do the trick.

like image 878
Pratheep Avatar asked May 29 '26 16:05

Pratheep


2 Answers

An important thing to understand that there is no array type in javascript. Built-in Array is just a convenience wrapped over the standard Object. The only difference is that Arrays have the length property, computed in a special way.

new Array(3) returns an object with a single length field. It doesn't contain any other keys.

{
   length: 3
}

[undefined, undefined, undefined] creates an object with 3 numeric slots:

{
   length: 3
   0: undefined,
   1: undefined,
   2: undefined,
}

That makes difference, because map and other iterators look for numeric keys that actually exist in the object. The logic behind map, forEach and friends is like this:

  for (var i = 0; i < A.length; i++)
      if (A.hasOwnProperty(i))
          do something with A[i]
like image 91
georg Avatar answered May 31 '26 07:05

georg


new Array(3)returns an array of length 3 containing 3 undefineds which is equivalent to [undefined, undefined, undefined];

Not according to MDN:

this implies an array of arrayLength empty slots, not slots with actual undefined values

like image 27
Hugues M. Avatar answered May 31 '26 05:05

Hugues M.