TypeError: .for is not iterable / array[Symbol.iterator]().next().value is not iterable

Viewed 3464

Given this code:

let arr = await fetch(...).then(r => r.json());
for(let [a, b] of arr) {
  console.log(a, b);
}

What could cause the cryptic/unhelpful error message .for is not iterable in Chromium/Node.js? On Firefox the error message is instead Uncaught TypeError: arr[Symbol.iterator]().next().value is not iterable.

This confused me for a few minutes so I figure until they make these error messages more friendly it'd be helpful to have an SO question/answer for it. See answer below.

1 Answers

This error occurs because the array contains non-arrays - e.g. it may contain objects like this:

let arr = [{a:1, b:2}, {a:3, b:4}];

So the for/of code should look like this instead:

for(let {a, b} of arr) {
  console.log(a, b);
}
Related