4

I am trying to create multiple div tags based on the value passed on to the function. ISo to do that in the function I create a new Array(x), Supposedly it should create an Array with x number of undefined pointers. But while console.log(theArray). It shows [empty * x] rather than undefined 3 times.

myFunction(value){
let myArray=new Array(value).map((_,key) => <div key={key}> Hi There</div>)
return myArray;

In the above function, suppose if I pass value =3, I expect myArray to contain 3 div tags with Hi There value. Instead it returns [empty *3].

Please tell me why is that?

jatin grover
  • 396
  • 1
  • 2
  • 10

2 Answers2

0

Array iteration methods won't loop over array indices that are holes

You could use Array#from() and it's built in mapper

let myArray=Array.from({length:value},(_,key) => <div key={key}> Hi There</div>)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

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));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44