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