We can check whether something iterable with JavaScript by checking whether the Symbol.iterator
property is inherited in the object.
To do this, we can use the in
operator:
const isIterable = (value) => {
return Symbol.iterator in Object(value);
}
console.log(isIterable([]))
console.log(isIterable(new Set()))
console.log(isIterable(new Map()))
console.log(isIterable('abc'))
console.log(isIterable(123))
We create the isIterable
function that checks whether Symbol.iterator
is in the value
object with the in
operator.
Then we see that the first 4 console logs are true
and the last one is false
since arrays, sets, maps, and strings are all iterable objects.
But numbers aren’t iterable objects.