In the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
The for...of
construct is described to be able to
Nowadays, as already stated, to test if obj
is iterable just do
obj != null && typeof obj[Symbol.iterator] === 'function'
The for..of construct is part of the ECMASCript 6th edition Language Specification Draft. So it could change before the final version.
In this draft, iterable objects must have the function iterator
as a property.
You can the check if an object is iterable like this:
function isIterable(obj){
if(obj === undefined || obj === null){
return false;
}
return obj.iterator !== undefined;
}
For async iterators you should check for the 'Symbol.asyncIterator' instead of 'Symbol.iterator':
async function* doSomething(i) {
yield 1;
yield 2;
}
let obj = doSomething();
console.log(typeof obj[Symbol.iterator] === 'function'); // false
console.log(typeof obj[Symbol.asyncIterator] === 'function'); // true