0

I found it strange that

Array(100).map(function (_, i) { return i + 1; })

returns [undefined, undefined, ... , undefined] rather than [1, 2, ..., 100], i. e. the mapping not happening. On the contrary, starting with an array of 100 undefined works (demo).

Does Array(100) returns something other than 100 undefined elements?

Pavlo
  • 43,301
  • 14
  • 77
  • 113
  • Where are you testing this? The `(v, i) => i + 1` syntax is ECMAScript 6 / "Harmony" syntax, I think, which I'm not sure if it's implemented in all current browser versions yet. Also, [`Array.prototype.map` documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). –  May 01 '14 at 18:38
  • Show some code to provide a picture to what and where do you get this. – All Blond May 01 '14 at 18:40
  • @Cupcake, change it to function () {} – it won't make difference. The arrow syntax currently works in Firefox. – Pavlo May 01 '14 at 18:51

1 Answers1

5

From the Array.prototype.map reference:

"callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted or which have never been assigned values."

The array that you create with Array(100) has a length of 100, but there are not items in it. An array containing 100 items that are undefined on the other hand has 100 items that have a value (that is the value undefined), so the callback will be called for each of them.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Ok, it looks like two different `undefined` here: not defined and defined with `undefined` value, right? – Pavlo May 01 '14 at 18:48
  • 2
    @Pavlo: Exactly. If you access an array item that is not set you will get the `undefined` value back, but that doesn't mean that it has the value `undefined`. The code `var v = Array(100);alert(0 in v);` will alert `false` as there is no item with index 0. – Guffa May 01 '14 at 18:57