René Roth René Roth - 7 months ago 14
Javascript Question

.map not working as expected on uninitiated array

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

Answer

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.

Comments