Checking whether something is iterable

The simplest solution is actually this:

if (Symbol.iterator in Object(value)) {

}

Object will wrap anything which isn't an object into one. This prevents the in operator from throwing exceptions and removes the need to check for edge cases. null and undefined become empty objects while strings are wrapped into iterable String objects.

I would personally recommend inlining this code instead of defining a function, as it is relatively short and less ambiguous than a call to some isIterable(x) function.


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.


Why so verbose?

const isIterable = object =>
  object != null && typeof object[Symbol.iterator] === 'function'

Tags:

Javascript