5

If I write this code: Array(3).map( () => ({ a:1 }) ) I get Array(3) [ <3 empty slots> ] instead of an array of 3 objects. Why is that?

As far as I know, Array(3) will produce an array of undefined elements with length 3. And for instance, [1, 2, 3].map( () => ({ a:1 }) ) produces the expected output. This is true also using any other array with length 3. I'm intrigued.

graciano
  • 310
  • 3
  • 10

1 Answers1

1

Array(3) creates an empty array of length 3. Or as an object it would be { length: 3 }. With, e.g. Array(Array(3)) you would create an array with undefineds { 0: undefined, 1: undefined, 2: undefined, length: 3 }. And .map only iterates over existing keys.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151