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)

3
  • 1
    I assume you meant return 'x' in your function b? Commented Jul 31, 2015 at 4:09
  • stackoverflow.com/questions/20222501/… Commented Jul 31, 2015 at 4: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 Commented Jul 31, 2015 at 4:13

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Good ole sparse arrays. TIL!
To be honest, I looked up the docs after seeing your question and TIL too! ;-)
haha awesome @techfoobar. If I only I did that too ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.