1

I'm using this design pattern analogously to C++'s std::vector::reserve:

> Array(3).map(k=>5)
[ <3 empty items> ]
> Array(3).fill(null).map(k=>5)
[ 5, 5, 5 ]

Clearly it's not a bug, as same functionality in Node.JS, Chrome and Firefox. But why does it act like this?

A T
  • 13,008
  • 21
  • 97
  • 158
  • 5
    _"`map` calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. **callback is invoked only for indexes of the array which have assigned values**..."_ – Andreas Jul 29 '17 at 07:46
  • Hmm, so here 'assigned values' includes assignment to `undefined`? - E.g.: this works also: `Array(3).fill(undefined).map(k=>5)` – A T Jul 29 '17 at 07:50
  • @AT Yes. I've should have posted the complete sentence... :( The missing part is: _"..., **including `undefined`**. 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.prototype.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)) – Andreas Jul 29 '17 at 07:53
  • `Array(3)` creates an object of type array with length 3, but there are no items available in that array so you can iterate over the array using its length with a loop but `map` iterates over the items of an array which in this case it has none. – Amin Jafari Jul 29 '17 at 08:04
  • btw, `null` !== `undefined`. – Nina Scholz Jul 29 '17 at 08:09
  • @NinaScholz yeah I know, that's why I posted it as something I was surprised that worked, whereas `null` came to no surprise. @Andreas: Hmm, strange. Well thanks for clearing this up! – A T Jul 29 '17 at 08:14

0 Answers0