liveBook · Manning

Iterator

As explained in Secrets of the JavaScript Ninja, Second Edition

An object that produces a sequence of values one at a time through an iteration protocol, typically using a next method.

A generator call creates an iterator instead of immediately running the generator body. The iterator lets you request values one at a time, either with next() or through a for...of loop. section 6.2

Each next() call runs the generator until its next yield, then returns an object containing the yielded value and a done flag. The generator suspends until another request; when it finishes, done is true and value is undefined. section 6.2.1

Iterators make generator-produced sequences useful for:

  • Requesting successive values, such as IDs from a generator with an ongoing loop. section 6.2.2
  • Traversing DOM nodes with a generator and for...of, as an alternative to recursive traversal. section 6.2.2
Listing 6.2. Controlling a generator through an iterator object
function* WeaponGenerator(){             #A
  yield "Katana";                        #A
  yield "Wakizashi";                     #A
}

const weaponsIterator = WeaponGenerator();   #B

const result1 = weaponsIterator.next();    #C
assert(typeof result1 === "object"         #D
    && result1.value === "Katana"          #D
    && !result1.done,                      #D
    "Katana received!");                   #D

const result2 = weaponsIterator.next();    #E
assert(typeof result2 === "object"         #E
    && result2.value === "Wakizashi"       #E
    && !result2.done,                      #E
    "Wakizashi received!");                #E

const result3 = weaponsIterator.next();    #F
assert(typeof result3 === "object"         #F
    && result3.value === undefined         #F
    && result3.done,                       #F
    "There are no more results!");         #F

Follow the iterator’s successive next() calls and compare each returned value and done flag. section 6.2.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Traces next() through yield, suspension, and value/done results, without generalizing beyond generator-created iterators.
Examples
Demonstrates weapon sequences, generated IDs, and generator-based traversal of a DOM tree.
What you can do after
Apply generator iterators with next() or for-of to request sequence values and traverse DOM nodes.
How it connects
Connects iterators to generator functions, yield, for-of loops, and DOM traversal.

Also explained in

Compare how 15 books explain iterator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.