Sikau

Advanced JavaScript · Day 13 · about 25 min

Iterators and iterables

What makes for...of work.

The secret behind for…of

for…of works on arrays, strings, Maps and Sets — but not plain objects. Why? Because those types follow the iterable protocol: they can hand out an iterator that produces values one at a time. You can make your own.

Iterators by hand

const letters = ["a", "b"];
const it = letters[Symbol.iterator]();
console.log(it.next());
console.log(it.next());
console.log(it.next());
const range = {
  from: 1,
  to: 4,
  [Symbol.iterator]() {
    let current = this.from;
    const last = this.to;
    return {
      next: () => (current <= last ? { value: current++, done: false } : { value: undefined, done: true }),
    };
  },
};

for (const n of range) console.log(n);
console.log([...range]);

The rest of this lesson

  • The protocol, step by stepexplain
  • Why lazy iteration mattersexplain
  • Predict the outputpredict
  • Calling next by handpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript