Check If a Value Is Iterable in JavaScript or Node.js

ECMAScript 2015 introduced the for..of and loops. Both loops allow you to iterate through values in a different way. Please find more details on the differences of both loops in the dedicated tutorial.

This tutorial focuses on how to determine whether a given value is actually iterable. JavaScript’s iteration protocol defines a Symbol.iterator that iterable values must implement. Read on to learn more!

Node.js Series Overview

  1. Check If a Value Is Iterable in JavaScript or Node.js

Check If a JavaScript Value is Iterable

JavaScript’s iteration protocol defines how to make a value iterable. In order to be iterable, an object must implement the @@iterator method.

You can also reference the @@iterator method using the Symbol.iterator constant. It points JavaScript to the same method. Symbol.iterator is a function that doesn’t accept arguments and returns an object following the iterator protocol.

You can use the Symbol.iterator constant to determine whether a given value is iterable. Make sure to exclude nullish values (undefined and null) and otherwise check for the existence of the @@iterator function:

 * Determine whether the given `input` is iterable.
 * @returns {Boolean}
function isIterable(input) {  
  if (input === null || input === undefined) {
    return false

  return typeof input[Symbol.iterator] === 'function'

That’s it!

Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.