liveBook · Manning

For...of

As explained in Secrets of the JavaScript Ninja, Second Edition

A JavaScript loop that iterates over iterable values using the iterator protocol.

A for...of loop consumes values from an iterator one at a time, hiding repeated next() calls and checks of each result’s done flag. section 6.2.1

Listing 6.1. Using a generator function to generate a sequence of values
function* WeaponGenerator(){                #A
  yield "Katana";                           #B
  yield "Wakizashi";                        #B
  yield "Kusarigama";                       #B
}

for(let weapon of WeaponGenerator()) {        #C
  assert(weapon !== undefined, weapon);       #C
}                                             #C

A generator yields a sequence of weapons that the loop consumes one value at a time. section 6.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains next() results through value and done, then characterizes for...of as shorthand for iterator control.
Examples
Uses WeaponGenerator to yield weapons and a warrior generator that delegates to a ninja generator.
What you can do after
Apply it to consume values yielded by a generator without writing iterator-control code.
How it connects
Links for...of to generator functions, iterators, and iterator results containing value and done.

Also explained in

Compare how 2 books explain for...of →

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.