2

I'd like to understand the why behind this:

var a = new Array(3);
var b = a.map(function () {
  return 'b';
});

results in

a: [ , , ]

b: [ , , ]

When I would expect b to result in ['b', 'b', 'b'].


In further investigation, I discovered that if i were to do a.push('a'), I'd have [, , , 'a'].

And after the map function, b would become [, , , 'b'].

What's going on here? Why do these allocated cells behave differently from the initialization? I was originally expecting this to act as it would if it was an array literal, [undefined, undefined, undefined].map(fn)

Atticus
  • 6,585
  • 10
  • 35
  • 57
  • 1
    I assume you meant `return 'x'` in your function `b`? – Marty Jul 31 '15 at 04:09
  • http://stackoverflow.com/questions/20222501/how-to-create-a-zero-filled-javascript-array-of-arbitrary-length – epascarello Jul 31 '15 at 04:12
  • javascript map function always return value which is in iterating array value only. Your array 'a' is empty of length 3. So it is returning same – Aravinder Jul 31 '15 at 04:13

1 Answers1

6

Array.map() does not invoke the callback for indexes whose values aren't defined.

From MDN docs:

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; it is not invoked for indexes that are undefined, those which have been deleted or which have never been assigned values.

techfoobar
  • 65,616
  • 14
  • 114
  • 135