4

Using .map() on an array full of undefined values (eg new Array(10)) will always return an array of the same length with undefined values, no matter what you return.

new Array(10).map(function(){return 5;});

will return a new array filled with 10x undefined. Why does this happen?

Screenshot

3
  • FYI this happens in both Google Chrome as well as NodeJS, so I think it's not an implementation-specific bug. Commented Apr 18, 2016 at 12:32
  • 1
    It's not a bug if it's documented :) Commented Apr 18, 2016 at 12:47
  • @TudorConstantin well, if we're being pedantic, I never said it is a bug :) Commented Jul 1, 2023 at 20:42

4 Answers 4

4

Because when you define an array like that, the spaces for values are empty slots and are not iterated over by map() or any of its friends.

There is Array.prototype.fill() (in ES6) which can be used to set values on that array.

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

2 Comments

So they are returned as-is, without executing the callback function? Bonus points for the fill() recommendation!
@RenéRoth The function just does nothing, but it will return a new array.
3

You could use

var array = Array.apply(null, { length: 10 }).map(function(){ return 5; });

var array = Array.apply(null, { length: 10 }).map(function() { return 5; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

Comments

2

from the fine manual:

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, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

new Array(10)

creates missing elements, if that makes any sense.

Like this one:

var b=new Array();
b[30] = 1;
var c = b.map(function(){return 5;});

> [undefined × 30, 5]

Comments

1

There's an answer for this here: https://stackoverflow.com/a/5501711/6206601. Look at the top comment for further clarification.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.