Skip to content

Chapter 25 of 33

Iterators and Iterables

Implement iteration protocols and integrate custom sequences with language syntax.

36 minutes 10 quick checksBy Subha Prasad
Lesson 25 of 33Course navigation

Lesson content

Read, practise, then check your understanding

An iterator’s next() returns { value, done }. An iterable provides [Symbol.iterator]() returning an iterator. Arrays, strings, maps, sets, spread, destructuring, and for...of use this protocol.

Custom iterable

const countdown = {
  from: 3,
  *[Symbol.iterator]() {
    for (let value = this.from; value > 0; value -= 1) yield value;
  }
};
console.log([...countdown]);

Return a fresh iterator when multiple independent traversals are expected. Iterators may implement return for early-exit cleanup and throw for injected failure. Async iterables implement Symbol.asyncIterator and are consumed with for await...of.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes iterable?
Which JavaScript term matches this description: An object with a Symbol.iterator method returning an iterator.
Which statement best describes iterator?
Which JavaScript term matches this description: An object whose next method returns value/done records.
Which statement best describes iterator protocol?
Which JavaScript term matches this description: The contract followed by next results and completion.
Which statement best describes for...of?
Which JavaScript term matches this description: Syntax consuming the iterable protocol.
Which statement best describes custom iterable?
Which JavaScript term matches this description: An object implementing Symbol.iterator for domain-specific traversal.

0 of 10 checks passed

Your progress is saved on this device.