Checking whether something is iterable

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.


The simplest solution is actually this:

function isIterable (value) {
  return Symbol.iterator in Object(value);
}

Object will wrap anything which isn't an object in one, allowing the in operator to work even if the original value is not an Object. null and undefined are turned into empty objects so there's no need for edge case detection, and strings get wrapped into String objects which are iterable.


Why so verbose?

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