1

I just want to get some more clarity over how map function works and also Array(n) method.

  • For relevance lets take two variables bucket and basket.
var bucket = Array(3);                      // Create an empty array of length of 3.
console.log(bucket);                        // Console shows > [null, null, null]
bucket.map((bucketItem, index)=>{           // Trying to run map method over bucket array
    console.log(index, bucketItem);         // Does not enter this scope.
});

var basket = [null, null, null];            // Create an empty array of length of 3.
console.log(basket);                        // Console shows > [null, null, null]
basket.map((basketItem, index)=>{           // Trying to run map method over basket array
    console.log(index, basketItem);         // Console shows > 0 null, 1 null, 2 null 
});

console.log(Array.isArray(bucket))          // Console shows > true, stating bucket is an array.
console.log(Array.isArray(basket))          // Console shows > true, stating basket is an array.

Now as shown above bucket and basket both return true, when checked for being an array but however map method doesn't execute for bucket variable, while it does for basket.

  • Now lets create a new variable newBucket using Array(n) method and ... Spread Operator.
var newBucket = [...Array(3)];              // Create an empty array of length of 3 and use it with spread opertor.
console.log(newBucket);                     // Console shows > [null, null, null]
newBucket.map((newBucketItem, index)=>{     // Trying to run map method over newBucket array
    console.log(index, newBucketItem);      // Console shows > 0 undefined, 1 undefined, 2 undefined 
});

console.log(Array.isArray(newBucket))       // Console shows > true, stating newBucket is an array.

However the map function now executes for newBucket and still newBucket is a valid array.

Could anyone please guide me on this front or share relevant link or point out materials for the same?

Thanking You, Sharat

Here is the link to the code

Dupocas
  • 20,285
  • 6
  • 38
  • 56

1 Answers1

1

Most of the Array iteration methods don't call the callback for elements that have never been assigned a value. That's the case for the elements of an array that's just been created via new Array(3).

You can use .fill() method to initialize all elements of a new array. When you use spread syntax, that will pay attention to the uninitialized elements, and so you end up with another new array with elements explicitly initialized to undefined.

Pointy
  • 405,095
  • 59
  • 585
  • 614