0

I'm trying to understand why JavaScript behaves this way. To generate numbers from 1 to n inclusive in an array,

The following works:

console.log(new Array(5).fill().map((a,i)=>i+1))  //Result [1,2,3,4,5] as expected.

But if I remove fill() it doesn't work:

console.log(new Array(5).map((a,i)=>i+1))  //Result [undefined,undefined,undefined,undefined,undefined]

Since the array is already initialized and we are mapping from the indices, why does the latter not work?

I tried both in jsFiddle. This is more about clarifying a concept than solving a problem.

0 Answers0