-1

According to my current JS understanding, All 3 lines below should return the same result, can someone please explain what I'm missing ?

1- Unexpected

[...Array(6).map((x) => 1)]
(6) [undefined, undefined, undefined, undefined, undefined, undefined]

2- expected

[...Array(6)].map((x) => 1)
(6) [1, 1, 1, 1, 1, 1]

3- unexpected

Array(6).map((x) => 1)
(6) [empty × 6]
kimododev
  • 11
  • 1
  • 1
  • 4
    `.map()` skips uninitialized elements. – Pointy Jan 27 '22 at 16:44
  • 3
    use `.fill()` to initialize the elements before mapping: `Array(6).fill().map(x => 1)` ----- better yet, cut the step, `Array(6).fill(1)` – skara9 Jan 27 '22 at 16:50
  • 1
    [See the `map` docs' "Description" section for details.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#description) – Dave Newton Jan 27 '22 at 16:58

1 Answers1

0

Array(n) creates an array of length n, but the array has no values in it so there is nothing to map over.

Basically, this:

const a = Array(n);

is the same as:

const a = [];
a.length = n;

This is why the created array has no elements in it. Attempting to map it will do nothing since there are no values to map.

You can, however, convert that empty array to an array of undefined values. This can be done in two ways:

One is using the spread operator as you have done:

[...Array(n)] // creates new array [undefined, undefined, undefined ...] n times

The other, more commonly used, is .fill(), which sets its parameter as the value for all the indices of the array. To fill with undefined, do:

Array(n).fill() // fills array with [undefined, undefined, undefined ...] n times

An array of undefined, unlike an empty array, has elements and can therefore be mapped:

[undefined, undefined, undefined].map(x => 1) // [1, 1, 1]

So you can first convert your empty array to an array of undefined, and then map it like so:

Array(n).fill().map(x => 1)

If you want to fill the array with the same element in each position like in this example, you can simply pass it in to fill without needing to map the array:

Array(n).fill(1)
skara9
  • 4,042
  • 1
  • 6
  • 21