Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether something is iterable

Tags:

javascript

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 iterate over "iterable" objects. But is there a good way of deciding whether an object is iterable?

I've tried to find common properties for arrays, iterators and generators, but have been unable to do so.

Aside from doing a for ... of in a try block and checking for type errors, is there a clean way of doing this?

like image 852
simonzack Avatar asked Sep 18 '13 23:09

simonzack


People also ask

How do you check if an object is iterable in JS?

We can check whether something iterable with JavaScript by checking whether the Symbol. iterator property is inherited in the object. We create the isIterable function that checks whether Symbol. iterator is in the value object with the in operator.

Are objects iterable Python?

Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables. In short and simpler terms, iterable is anything that you can loop over.

Is a JavaScript object iterable?

In JavaScript, Object s are not iterable unless they implement the iterable protocol. Therefore, you cannot use for...of to iterate over the properties of an object.

Which datatype is iterable in Python?

Examples of iterables include all sequence types (such as list , str , and tuple ) and some non-sequence types like dict , file objects, and objects of any classes you define with an __iter__() method or with a __getitem__() method that implements Sequence semantics.


1 Answers

The proper way to check for iterability is as follows:

function isIterable(obj) {   // checks for null and undefined   if (obj == null) {     return false;   }   return typeof obj[Symbol.iterator] === 'function'; } 

Why this works (iterable protocol in depth): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols

Since we are talking about for..of, I assume, we are in ES6 mindset.

Also, don't be surprised that this function returns true if obj is a string, as strings iterate over their characters.

like image 57
Tomas Kulich Avatar answered Oct 14 '22 03:10

Tomas Kulich