Difference between Array(n) and Array(n).fill?

map only operates on defined integer properties of an array. Array(n) does not set integer properties, while Array(n).fill() does. There's a difference between a property that doesn't exist and an extant property whose value is undefined.

Array(n) sets the length property of the array, but it does not set any properties. The array object does not have any integer properties.

.fill sets all of the integer properties for an array from zero up to one less than length. When you do Array(n) you set the length property of the new aray, and then .fill() defines and sets each integer property up to n-1. The array created by Array(n).fill() does have properties defined up to length - 1. (The properties happen to be set to undefined, because you didn't pass an argument to fill, but they do exist.)

In pracitcal terms, you can see the difference if you do Object.keys(Array(4)) (empty array) versus Object.keys(Array(4).fill()) (a list of strings "0" to "3"). In the first case, the properties don't exist; in the second case they do.


Array(n) creates a new array of size n, the contents have not been defined.

Array(n).fill() creates an array of size n where every element is set to whatever you passed into fill or undefined in your case since you passed nothing.

Array(n).fill('test') creates an array of size n filled with 'test'.