All posts

Fix Iterator Protocol Error in Node.js

Resolve 'is not iterable' and iterator protocol errors in Node.js by implementing Symbol.iterator correctly on custom objects.

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 without Symbol.iterator
  • An async generator being consumed with a sync for...of instead of for 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 Free