Solve - is not iterable TypeError in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Martin Balle

Solve - is not iterable TypeError in JavaScript #

The "is not iterable" error occurs when using the for...of loop with a right hand-side value that is not iterable, e.g. an object. To solve the error, use the Object.keys() or Object.values() methods to get an array with which you can use the for...of loop.

typeerror is not iterable

Here's an example of how the error occurs.

index.js
const obj = {name: 'Tom', age: 30}; // โ›”๏ธ TypeError: obj is not iterable for (const key of obj) { console.log(key); }

We used the for...of loop to try to iterate over an object.

Since objects are not iterable, we got the "obj is not iterable" error.

Instead, you should use the Object.keys(), Object.values() or Object.entires() methods to get an array which you can use with the for...of loop.

index.js
const obj = {name: 'Tom', age: 30}; // โœ… Using Object.keys() for (const key of Object.keys(obj)) { console.log(key); // ๐Ÿ‘‰๏ธ name, age console.log(obj[key]); // ๐Ÿ‘‰๏ธ 'Tom', 30 } // โœ… Using Object.values() for (const value of Object.values(obj)) { console.log(value); // ๐Ÿ‘‰๏ธ Tom, 30 } // โœ… Using Object.entries() for (const entry of Object.entries(obj)) { console.log(entry); // ๐Ÿ‘‰๏ธ ['name', 'Tom'], ['age', 30] }

To iterate over a value, it has to be an iterable, e.g. array, string, Map, Set, generator, etc.

We used the Object.keys method to get an array of the objects keys we can iterate over using a for...of loop.

Similarly, you can call the Array.forEach method on the array the method returns.

index.js
const obj = {name: 'Tom', age: 30}; Object.keys(obj).forEach(key => { console.log(key); // ๐Ÿ‘‰๏ธ name, age console.log(obj[key]); // ๐Ÿ‘‰๏ธ 'Tom', 30 });

The Object.values method returns an array of the object's values and the Object.entries() method returns an array of arrays, where each inner array contains 2 elements - the key and the corresponding value - [key, value].

If you need to iterate over a generator function, you can use the for...of loop.

index.js
function* generator(a, b, c) { yield a; yield b; yield c; } for (const num of generator(5, 10, 15)) { console.log(num); // ๐Ÿ‘‰๏ธ 5, 10, 15 }

Notice that we had to call the function for it to return the generator object we can iterate over.

If you forget to call the function, you would get the "is not iterable" TypeError back.

index.js
function* generator(a, b, c) { yield a; yield b; yield c; } // โ›”๏ธ generator is not iterable for (const num of generator) { console.log(num); }

We forgot to call the function, so we passed a right hand-side value of a function to the for...of loop, which caused the error.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee