new Array(len)
creates an empty array, and does something different than filling it with undefined
values: It sets its length to len
. So, it translates to this code:
var newArr = [];
newArr.length = len;
Let's have some fun with newArr
(assuming that len = 4
):
newArr.length; //4
newArr[1] === undefined; //true
newArr.hasOwnProperty(1); //false
This is because while the is 4 items long, it does not contain any of these 4 items. Imagine an empty bullet-clip: It has space for, say, 20 bullets, but it doesn't contain any of them. They weren't even set to the value undefined
, they just are...undefined (which is a bit confusing.)
Now, Array.prototype.map
happily walks along your first array, chirping and whistling, and every time it sees an array item, it calls a function on it. But, as it walks along the empty bullet-clip, it sees no bullets. Sure, there are room for bullets, but that doesn't make them exist. In here, there is no value, because the key which maps to that value does not exist.
For the second array, which is filled with undefined
values, the value is undefined
, and so is the key. There is something inside b[1]
or b[3]
, but that something isn't defined; but Array.prototype.map
doesn't care, it'll operate on any value, as long as it has a key.
For further inspection in the spec:
new Array(len)
: http://es5.github.com/#x15.4.2.2
Array.prototype.map
: http://es5.github.com/#x15.4.4.19 (pay close attention to step 8.b)