liveBook · Manning

For...of

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A JavaScript looping statement that iterates over iterable values by repeatedly obtaining successive items from an iterator.

Use `for...of` to visit the values of an iterable one at a time. Unlike `for...in`, which enumerates an object’s property names, `for...of` works with iterable values. section 23.2 section 23.1

Listing 23.1. Comparing for..in and for..of
const obj = { series: "Get Programming", publisher: "Manning" }; const arr = [ "Get Programming", "Manning" ]; for (const name in obj) { console.log(name); 1 } for (const name of arr) { console.log(name); 2 }

Compare a `for...in` loop over an object with a `for...of` loop over an array. section 23.2

Compared with `forEach`, `for...of`:

  • Works with any iterable, not only arrays. section 23.2
  • Can exit early with `break`. section 23.2
  • Can yield from a generator loop; `yield` inside a `forEach` callback instead produces a syntax error. section 23.2

Build a deck

Nested `for...of` loops visit each suit and face, adding a card for every combination to a `Set`. section 26.1

Listing 26.5. src/cards.js
export function createDeck() { const deck = new Set(); for (const suit of suits) { for (const face of faces) { deck.add({ face, suit }); } } shuffle(deck); return deck; }

See the deck-building function that uses nested `for...of` loops. section 26.1

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Defines value iteration, compares it with for...in and forEach, and demonstrates early exit and generator use without detailing iterator internals.
Examples
Contrasts object-key and array-value loops, then uses nested loops to create a card deck from suits and faces.
What it assumes
Uses the iterable protocol to explain the loop and identifies strings, arrays, Sets, and Maps as iterable examples.
What you can do after
Apply it to process iterable values, stop early with break, or yield values from a generator loop.
How it connects
Connects iterable protocol, for...in, Array.prototype.forEach, spread syntax, and generator functions.

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 Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.