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)]);
Snirka
  • 602
  • 1
  • 5
  • 19
  • 1
    `Array(1)` creates an array with 1 empty slot. Spreading it makes an array with one item which is `undefined`. – VLAZ Jun 27 '21 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`? –  Jun 27 '21 at 14:43
  • 1
    @jabaa [Yes, they're different](https://stackoverflow.com/questions/11266126/undefined-values-in-arraylen-initializer), even if accessing them gives `undefined` for both – Bergi Jun 27 '21 at 14:43
  • So many duplicates and I haven't found even one of them –  Jun 27 '21 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`. – VLAZ Jun 27 '21 at 14:46
  • Well you can find them only if you know exactly what to search for… (or have bookmarked them) and I found one but VLAZ found another. – Bergi Jun 27 '21 at 14:46

0 Answers0