Categories
JavaScript Answers

How to Fix the ‘TypeError: ‘x’ is not iterable’ Error in Our JavaScript App?

Spread the love

Sometimes, we may run into the ‘TypeError: ‘x’ is not iterable’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘TypeError: ‘x’ is not iterable’ when we’re developing JavaScript apps.

Fix the ‘TypeError: ‘x’ is not iterable’ When Developing JavaScript Apps

To fix the ‘TypeError: ‘x’ is not iterable’ when we’re developing JavaScript apps, we should make sure we’re using the for-of loop on an object that’s iterable like an array, set, map, string, etc.

On Firefox and Chrome, the error message for this error is TypeError: 'x' is not iterable.

On Chrome, the message TypeError: 'x' is not a function or its return value is not iterable is also sometimes shown for this error.

For instance, if we try to iterate through a non-iterable object:

const obj = { 'France': 'Paris', 'England': 'London' };
for (let p of obj) { 
  // ...
}

then we’ll get this error.

Instead, we can use Object.entries to get the key-value pair array and we can use the for-of loop with that:

for (const [country, capital] of Object.entries(obj)) {
  console.log(country, capital);
}

If we’re iterating over a generator function, we should make sure we call it before we iterate through the returned items.

For instance, the following will throw this error:

function* generate(a, b) {
  yield a;
  yield b;
}

for (const x of generate) {
  console.log(x);
}

The function itself isn’t iterable, so we get this error.

Instead, we write:

function* generate(a, b) {
  yield a;
  yield b;
}

for (const x of generate(1, 2)) {
  console.log(x);
}

to iterated through the returned items.

Conclusion

To fix the ‘TypeError: ‘x’ is not iterable’ when we’re developing JavaScript apps, we should make sure we’re using the for-of loop on an object that’s iterable like an array, set, map, string, etc.

On Firefox and Chrome, the error message for this error is TypeError: 'x' is not iterable.

On Chrome, the message TypeError: 'x' is not a function or its return value is not iterable is also sometimes shown for this error.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *