Iterator Protocol Errors in Node.js
You've probably seen TypeError: X is not iterable or X is not a function when using for...of, spread syntax, or destructuring. This means the object you're iterating doesn't implement the iterator protocol.
When This Happens
- Passing a plain object to
for...of(objects aren't iterable by default) - Spreading a non-iterable value:
[...myObj] - Using
Array.from()on something withoutSymbol.iterator - An async generator being consumed with a sync
for...ofinstead offor await...of
Quick Fix for Objects
const config = { host: 'localhost', port: 3000, env: 'dev' };
// ERROR: config is not iterable
// for (const item of config) { ... }
// Fix: iterate over entries
for (const [key, value] of Object.entries(config)) {
console.log(`${key}: ${value}`);
}Custom Iterable Class
If you want your own class to be iterable:
class NumberRange {
constructor(start, end) {
this.start = start;
this.end = end;
}
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next() {
return current <= end
? { value: current++, done: false }
: { done: true };
}
};
}
}
const range = new NumberRange(1, 5);
console.log([...range]); // [1, 2, 3, 4, 5]Async Iterators
Don't forget to use for await...of with async generators:
for await (const chunk of readableStream) {
process.stdout.write(chunk);
}Bugsly captures these TypeErrors with full stack traces, including the variable name and call site, so you can pinpoint exactly which value wasn't iterable.
Try Bugsly Free
AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.
Get Started FreeRelated Articles
How to Fix Validationerror in FastAPI In Production
A practical guide to resolving Validationerror in FastAPI in production, with real code examples and debugging tips.
Read moreHow to Fix Query Error in Svelte
Learn how to diagnose and fix the query error in Svelte. Includes code examples and prevention tips.
Read moreHow to Fix Geolocation Permission Denied in Angular
Learn how to fix the Geolocation Permission Denied in Angular. Step-by-step guide with code examples.
Read moreHow to Fix CORS Policy Blocked Error in Node.js
Learn how to fix the CORS Policy Blocked Error in Node.js. Step-by-step guide with code examples.
Read more