Sometimes, we want to check whether something is iterable in JavaScript.
In this article, we’ll look at how to check whether something is iterable in JavaScript.
How to check whether something is iterable in JavaScript?
To check whether something is iterable in JavaScript, we can check if the Symbol.iterator
property of the object if a function.
For instance, we write
const isIterable = (obj) => {
if (obj === null || obj === undefined) {
return false;
}
return typeof obj[Symbol.iterator] === "function";
};
to check if obj
is null
or undefined
with
obj === null || obj === undefined
If it is, then we return false
.
Otherwise, we check if the obj
‘s Symbol.iterator
property is a function with
typeof obj[Symbol.iterator] === "function"
If that’s true
, then obj
is an iterable object.
Conclusion
To check whether something is iterable in JavaScript, we can check if the Symbol.iterator
property of the object if a function.