TypeError: x is not iterable
TypeError: x is not iterable in JavaScript means you used a for...of loop or spread operator (...x) on something that is not an array, string, or iterable — most often a plain object, null, or undefined.
How do I fix TypeError: x is not iterable?
To fix TypeError: x is not iterable in JavaScript, locate the line causing the error and check the values right before it runs. Most occurrences happen because of using for...of on a plain object. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does TypeError: x is not iterable mean?
In JavaScript, iteration protocols are implemented by Arrays, Strings, Maps, Sets, and generators. Plain objects ({ key: value }) are not iterable by default. When you try to for...of over an object or spread it into an array, JavaScript throws TypeError.
Why does TypeError: x is not iterable happen?
1. Using for...of on a plain object
Plain objects do not have a Symbol.iterator property.
Breaks
const user = { name: "Ada", age: 36 };
for (const val of user) {
console.log(val);
}Works
const user = { name: "Ada", age: 36 };
for (const val of Object.values(user)) {
console.log(val);
}2. Spreading a value that is undefined or null
If data has not loaded or is missing, spreading it into an array throws.
Breaks
const items = [...data.results];Works
const items = [...(data?.results ?? [])];3. A function returned an error object instead of a list
An API response returning { error: "Not found" } cannot be looped over with for...of.
Breaks
for (const item of await fetchItems()) { /* ... */ }Works
const items = await fetchItems();
if (Array.isArray(items)) {
for (const item of items) { /* ... */ }
}How to find it in your own code
Use `Object.entries(obj)` or `Object.values(obj)` to iterate over plain objects, and guard spreads with default fallbacks like `[...(items ?? [])]`.
Try it: fix this bug
easycountPositives([3, -1, 4]) throws TypeError: Assignment to constant variable.
function countPositives(nums) {
const count = 0;
for (const n of nums) {
if (n > 0) {
count++;
}
}
return count;
}More challenges with this error
Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser — no install, no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.