TypeError: 'x' is not iterable (Firefox, Chrome) TypeError: 'x' is not a function or its return value is not iterable (Chrome)
The value which is given as the right hand-side of for…of or as argument of a function such as Promise.all
or TypedArray.from
, is not an iterable object. An iterable can be a built-in iterable type such as Array
, String
or Map
, a generator result, or an object implementing the iterable protocol.
In JavaScript, Object
s are not iterable unless they implement the iterable protocol. Therefore, you cannot use for…of to iterate over the properties of an object.
var obj = { 'France': 'Paris', 'England': 'London' }; for (let p of obj) { // TypeError: obj is not iterable // … }
Instead you have to use Object.keys
or Object.entries
, to iterate over the properties or entries of an object.
var obj = { 'France': 'Paris', 'England': 'London' }; // Iterate over the property names: for (let country of Object.keys(obj)) { var capital = obj[country]; console.log(country, capital); } for (const [country, capital] of Object.entries(obj)) console.log(country, capital);
Another option for this use case might be to use a Map
:
var map = new Map; map.set('France', 'Paris'); map.set('England', 'London'); // Iterate over the property names: for (let country of map.keys()) { let capital = map[country]; console.log(country, capital); } for (let capital of map.values()) console.log(capital); for (const [country, capital] of map.entries()) console.log(country, capital);
Generators are functions you call to produce an iterable object.
function* generate(a, b) { yield a; yield b; } for (let x of generate) // TypeError: generate is not iterable console.log(x);
When they are not called, the Function
object corresponding to the generator is callable, but not iterable. Calling a generator produces an iterable object which will iterate over the values yielded during the execution of the generator.
function* generate(a, b) { yield a; yield b; } for (let x of generate(1,2)) console.log(x);
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/is_not_iterable