Why can't I map new Array(3) into an array of new values? [duplicate]

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)



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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.