René Roth René Roth - 6 months ago 9x
Javascript Question

.map not working as expected on uninitiated array


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?



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.