2

Following code gives empty object {}:

{ 2, {...undefined}}

But why does below code gives error: Uncaught TypeError: undefined is not iterable?

{ 2, [...undefined]}
Prasanth Kanna
  • 1,961
  • 4
  • 18
  • 25
  • Indeed that is true. What is your question? – trincot Nov 08 '21 at 10:21
  • Assuming you are using keys in both of your objects (or you meant to use `[]` instead of `{}` as your outermost brackets), otherwise, you'll get "Uncaught SyntaxError: Unexpected number" with both examples – Nick Parsons Nov 08 '21 at 10:23
  • @NickParsons `{ 2, {...undefined} }` works in chrome's console. It probaby considers `{}` as a block and returns the result of the the comma operator. – adiga Nov 08 '21 at 10:28
  • @adiga ah good point, that's most likely how OP is running the above code – Nick Parsons Nov 08 '21 at 10:31

1 Answers1

-2

You cannot destructure an array if it's not an array for sure. It's ok to have an empty array so the given value will be undefined.

You can use this to prevent access undefined OR non-iterable value:

const a = undefined
console.log(...(a ?? []))

Aviv Ben Shahar
  • 268
  • 1
  • 8