• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

182
Views
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?

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

(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.

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error