3

Why is the behavior different for javascript arrays created with new?

(new Array(10)).length

10

var x = 0;
(new Array(10)).forEach(function(){ console.log(++x) });

: nothing - Why?

var x = 0;
[undefined,undefined,undefined].forEach( function(){console.log(++x)});

1

2

3

jcampbell1
  • 4,159
  • 3
  • 33
  • 35
  • 1
    Sparse arrays are confusing in Javascript. Try to avoid them. – Barmar Dec 19 '13 at 20:52
  • 1
    An alternative would be this: `Array.apply(null, Array(10)).forEach(....` – cookie monster Dec 19 '13 at 20:54
  • Try this (to see that it's not *really* an issue with `new Array`): `var a = []; a[10] = "done"; a.forEach(console.log.bind(console))`. It's in the definition of `forEach` and `map` to skip "non existent elements". – user2864740 Dec 19 '13 at 21:02

0 Answers0