'Can figure out the difference using spread operator in array and object in JavaScript

I am using spread operator in an array like below:

const addOne = false;
const arr = [1, 2, 3]
const arr1 = [...arr, ...(addOne && [8, 9])];
console.log(arr1)

And I got the error

TypeError: (addOne && [8,9]) is not iterable
    at <anonymous>:4:32

While if I use spread operator in an object like:

const addOne = false;

const obj = {
  name: 'peter',
  age: 23
}
const obj1 = {
  ...obj,
  ...(addOne && obj)
}
console.log(obj1)

it prints out the correct output

Anyone knows why?



Solution 1:[1]

(false && obj) evaluates to a boolean so its' not iterable.
When using the spread operator when building your obj1 object, js uses a different method to extract the key value pairs from an object (remember that a bool value in js is still an object), so it won't throw an error since it's expecting an object as an input.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 michmich112