1

What's the difference between Array(1) and [...Array(1)]? I was sure that both are equivalent until I saw that both behave differently regarding .map:

console.log(Array(1).map(() => 1));
console.log([...Array(1)].map(() => 1));

Why do they behave differently even though both return [undefined]?

console.log(Array(1));
console.log([...Array(1)]);

6
  • 1
    Array(1) creates an array with 1 empty slot. Spreading it makes an array with one item which is undefined. Commented Jun 27, 2021 at 14:38
  • @VLAZ That means that an empty slot and undefined are different but when I try to access an empty spot I get undefined? Commented Jun 27, 2021 at 14:43
  • 1
    @jabaa Yes, they're different, even if accessing them gives undefined for both Commented Jun 27, 2021 at 14:43
  • So many duplicates and I haven't found even one of them Commented Jun 27, 2021 at 14:45
  • @jabaa yes. If you have an object obj = {a: 1, c: 3} then obj.b will give you undefined. That's what an empty slot is - it doesn't exist. But if you try to read its value, you get undefined. Array iteration methods such as .map will skip over empty slots and only act on existing items, even if those items are undefined. Commented Jun 27, 2021 at 14:46

0