How to use iterators and iterables in JavaScript

· Category: JavaScript

Short answer

An iterable implements Symbol.iterator and returns an iterator with a next() method. for...of consumes iterables by calling next() until done is true.

Steps

  1. Built-in iterables: javascript for (const char of "hello") { console.log(char); } for (const item of [1, 2, 3]) { console.log(item); }
  2. Create a custom iterable: javascript function range(start, end) { return { [Symbol.iterator]() { let current = start; return { next() { if (current <= end) { return { value: current++, done: false }; } return { done: true }; } }; } }; } for (const n of range(1, 3)) console.log(n);

Tips

  • Iterators are stateful; each for...of call requests a fresh iterator.
  • Generators provide a concise syntax for creating iterators.

Common issues

  • Objects are not iterable by default; use Object.keys, Object.values, or Object.entries to iterate.
  • Infinite iterators without a break condition cause infinite loops.