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?
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.
Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables. In short and simpler terms, iterable is anything that you can loop over.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With