0

So I noticed today that if you create an Array using the non-usual new Array(<array_length>) syntax, you will be unable to map over the values correctly.

A simple example:

var newArr = new Array(10);

newArr = newArr.map(function(val) {
  alert("It's really happening!");
  return 200;
});


console.log(newArr);

The result after running is still an empty array, nor does any of the alert's fire off.

Any ideas why the new Array()s passed in .map() function doesn't work in this example?

AlbertEngelB
  • 16,016
  • 15
  • 66
  • 93
  • 3
    Because `.map` ignores "holes". See http://es5.github.io/#x15.4.4.19 – Felix Kling Sep 17 '14 at 20:33
  • @FelixKling If I do `[undefined,undefined,undefined.map()` the methods will fire. I guess this works because it still technically has the values there? – AlbertEngelB Sep 17 '14 at 20:35
  • 2
    Yes, in every possible sense the array has three elements (each of them is the value `undefined`)) (`console.dir([undefined,undefined,undefined])`). That's not the case with `Array(x)` (`console.dir(Array(3))`). The latter basically just sets `length` to `3`. – Felix Kling Sep 17 '14 at 20:36
  • Put differently, we are talking about the difference between `({0: undefined}[0])` and `({}[0])`. The first one returns `undefined` because the value of the property `0` is `undefined`. The second one is `undefined` because accessing a non-existing property returns `undefined`. The second has the "hole". – Felix Kling Sep 17 '14 at 20:42
  • @FelixKling Ahh, that makes sense. Also bonus points to the downvoters, appreciate it. – AlbertEngelB Sep 17 '14 at 20:42
  • 1
    String(Array(10)).split(",") – dandavis Sep 17 '14 at 22:20

0 Answers0