1

I was trying to create an array which is [1,2,3,...,n], so I used code new Array(10).map((value,index)=>index+1), but I got [empty × 5];

Meanwhile, new Array(10).fill(1).map((value,index)=>index+1), why?

How did Array.prototype.map() work?

My code:

// [empty × 10]
new Array(10).map((value,index)=>index+1)

// [1,2,...,10]
new Array(10).fill(1).map((value,index)=>index+1)
G.J
  • 11
  • 1

1 Answers1

0

As per MDN docs:

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).


In your first case, You are just creating an array of a certain length without setting any value so it won't call the map callback. In the second method, you are setting all values to 1 using Array#fill method so it will call the callback since the value is assigned for all index.


You can use Array.from method with a map callback for generating an array.

const arr = Array.from({ length: 10 }, (_, i) => i + 1)

console.log(arr)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188