Tip: Make any JavaScript value iterable

JavaScript, Array, Iterator, Generator · Jun 12, 2021

JavaScript's Symbol.iterator is a very powerful tool that every web developer should learn how to use. It allows you to define and customize the way a value is iterated, effectively allowing you to make any value iterable. You can easily apply this knowledge to plain JavaScript objects and even classes.

All you need to correctly define an iterator is a generator function yielding each of the iteration values. This could be used to retrieve key-value pairs in an object, call specific getter functions from a class or split a number into an array of digits:

const obj = { a: 1, b: 2, c: 3 };

obj[Symbol.iterator] = function* () {
  for (let key of Object.keys(obj)) yield { [key]: obj[key] };
};

[...obj]; // [ { a: 1 }, { b: 2 }, { c: 3 }]

class IterableNumber extends Number {
  *[Symbol.iterator]() {
    for (let digit of [...`${this}`].map(d => Number.parseInt(d))) yield digit;
  }
}

const num = new IterableNumber(1337);
[...num]; // [ 1, 3, 3, 7]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Generator Functions

    JavaScript generator functions are a more advanced yet very powerful JavaScript ES6 feature, which you can start using in your code right now.

    Collection · 17 snippets

  • Pull values from array based on function

    Mutates the original array to filter out the values specified, based on a given iterator function.

    JavaScript, Array · Oct 22, 2020

  • Iterable to hash

    Reduces a given iterable into a value hash (keyed data store).

    JavaScript, Array · Jan 30, 2022

  • Flat iterator

    Creates a generator that iterates over an iterable, flattening nested iterables.

    JavaScript, Array · Mar 9, 2022