Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  83] [ 6]  / answers: 1 / hits: 85621  / 11 Years ago, wed, september 18, 2013, 12:00:00

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?


More From » javascript

 Answers
2

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.


[#75607] Tuesday, September 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
albert

Total Points: 652
Total Questions: 105
Total Answers: 108

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;