If you look at how Array.prototype.map
is implemented under the hood by taking a look at the polyfill, you would see that there is a check for the index of iteration during the iteration of the given array before invoking the mapping callback.
So for an array having only undefined values the check for the index in the given array returns false
:
console.log(0 in [, , ]); // prints false
console.log(0 in [1, 2, 3]); //prints true
So the if condition cheeking the index is not satisfied and the callback you supplied is never executed so you get back a new array having len
number of undefined values.
This is the snippet of code from the map
polyfill:
//k is the index
k = 0;
//len is the length of the array
while (k < len) {
var kValue, mappedValue;
//O is the array and this condition will be false
if (k in O) {
kValue = O[k];
//your callback will be called here
mappedValue = callback.call(T, kValue, k, O);
//a new array is populated with the mapped value and returned
A[k] = mappedValue;
}
k++;
}
The Array.prototype.map
polyfill can be found here.
To prevent this you can use Array.prototype.fill
to fill the array with a value before invoking the map
:
function myFunction(value){
let myArray = new Array(value).fill(0).map((_,key) => `<div key={key}> Hi There</div>`);
return myArray;
}
console.log(myFunction(3));