0

JS Code Example:

[1,2,...undefined]
throw error: Uncaught TypeError: undefined is not iterable.
but, use object destructuring
{a: 1, b: 2, ...undefined} = {a: 1, b: 2}

Why?

Derek Mar
  • 3
  • 1
  • 4
    The first line isn't destructuring - it's spreading and you cannot spread `undefined`. You can, however, assign to it, which is why the second one works. – VLAZ Sep 15 '20 at 05:09
  • One can only iterate data-types, which implement iterable (similar to Java). – Martin Zeitler Sep 15 '20 at 05:11
  • 1
    `...` means different things in different contexts. https://stackoverflow.com/a/37152508/218196 – Felix Kling Sep 15 '20 at 05:14

1 Answers1

1

In your first line, you are unpacking a variable with the ... syntax, called spreading and are expecting a value in that position of the array.

In your second line, you are not spreading, you're using "rest properties" but you're not expecting a value back from the spreading of undefined, so that's why it's simply ignored and treated as empty.

Moe
  • 462
  • 2
  • 16
  • 2
    The second case is not using "spread". They are using something that I would call "rest properties". All the renaming properties (of which there are none), are collected in a new object and assigned to `undefined` (which is readonly). – Felix Kling Sep 15 '20 at 05:24