JavaScript Answers

How to Check Whether Something is Iterable with JavaScript?

Spread the love

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(new Set()))
console.log(isIterable(new Map()))

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.

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 *