Categories
JavaScript Answers

How to check whether something is iterable in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *