javascriptarraysdictionaryecmascript-6

Why does `Array(3).map(x => 42)` return an empty array instead of `[42, 42, 42]` in JavaScript?


I was brushing up on Array for an implementation and I stumbled on this discovery, I expected the following code to give me an array filled with the number 42:

Array(3).map(x => 42)

But instead, the result is:

[empty × 3]

console output

If I try the same with fill, which I normally use, it works as I expected:

Array(3).fill(42) // [42, 42, 42]

Or if I create the array explicitly:

[1, 2, 3].map(x => 42) // [42, 42, 42]

So clearly map works normally on an array with values as I've also known.

But why does Array(3).map(...) behave differently, and what does [empty × 3] actually mean in JavaScript? It's my first time coming across this.


Solution

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#using_map_on_sparse_arrays

    The array you created with Array(3) is a sparse array where all elements are empty, and map doesn't call the callback function on the empty elements, so map passes through the array and returns the array unchanged. This is why your code doesn't work