🟢 EasyModern JS📖 Theory Question

What are Iterators and Iterables in JavaScript?

💡

Hint

Iterator has next() → {value, done}. Iterable has [Symbol.iterator](). Used by for...of, spread, destructuring.

Full Answer

The iteration protocol standardizes how values are produced sequentially.

  • Iterator: an object with next() that returns { value, done }
  • Iterable: an object with [Symbol.iterator]() that returns an iterator
// Custom iterable range object
const range = {
  from: 1, to: 5,
  [Symbol.iterator]() {
    let current = this.from;
    const last = this.to;
    return {
      next() {
        return current <= last
          ? { value: current++, done: false }
          : { value: undefined, done: true };
      }
    };
  }
};

for (const n of range) console.log(n); // 1, 2, 3, 4, 5
[...range];   // [1, 2, 3, 4, 5]
const [a, b] = range; // destructuring works too

// Built-in iterables: Array, String, Map, Set, NodeList, arguments
for (const char of 'hello') console.log(char); // h, e, l, l, o

// Manual iteration
const iter = [1, 2][Symbol.iterator]();
iter.next(); // { value: 1, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: undefined, done: true }
💡 Anything that works with for...of, spread (...), or destructuring must be iterable. Implement [Symbol.iterator] to make your custom classes work with all these.

More Modern JS Questions

🟡 MediumWhat are generators and when would you use them?→🟢 EasyWhat is optional chaining (?.) and nullish coalescing (??)?→🟢 EasyWhat are tagged template literals and what are they used for?→🟢 EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint