Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

The issue

When we try to use the spread syntax with an non iterable that’s when we got into the following issue:

Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

The reason

We were trying the following code where we wanted to convert an object to array elements like below:

var obj = { foo: 'bar', x: 50 };
var newObj = [...obj];
console.log(newObj);

As soon as we run the above code we got into the above issue. As the obj is not an iterable, the spread syntax throws the above error. The spread syntax works with the iterable such as array, string etc.

The solution

Instead of making it as an array if we make this as object then it works. The ES6 supports spread syntax with object literals. So we could write the following code to solve this:

var obj = { foo: 'bar', x: 50 };
var newObj = {...obj};
console.log(newObj);
Share