liveBook · Manning

Iterable

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

An object or value that can be traversed element by element by the iteration protocol.

Want an array’s values rather than its indices? `for..in` visits the indices; `for..of` visits values. An iterable is an object that can supply values one at a time through JavaScript’s iterable protocol. Arrays, strings, sets, and maps are built-in examples. Spread syntax can collect an iterable’s values into an array. section 23.0 section 23.1

The key is a `[Symbol.iterator]` method, also called `@@iterator`. It returns a new iterator whose `next()` method supplies a `{value, done}` result. Each call advances the sequence; `done: true` says there are no more values. `for..of` and spread keep requesting values until then. An infinite iterable never reaches that point, so spreading one will not finish. section 23.4 section 23.5

function* primesIterator () {
  yield 2
  yield 3
  yield 5
}

const primesIterable = {
  [Symbol.iterator]: primesIterator
}

const myPrimes = [ ...primesIterable ]       1
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":10,\"ch\":45},{\"line\":10,\"ch\":46}]]"}
!@%STYLE%@!

A generator makes a short custom iterable: each `yield` supplies the next value, and `[...primesIterable]` produces `[2, 3, 5]`. It avoids writing `next()` and its result objects by hand. section 23.4

Try a bounded read

Write `take(n, iterable)` to collect at most `n` values. Test it with an infinite iterable and request ten values. Stop after ten requests—or sooner if `next()` reports `done: true`—rather than spreading the entire iterable. section 23.5

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

How deep it goes
Explains `Symbol.iterator`, iterator creation, `next()`, `value`, and `done`, then shows a generator as a shorter implementation.
Examples
Uses prime-number iterators, string-character spread, and an exercise that takes ten values from an infinite iterable.
What it assumes
Builds on familiarity with arrays, strings, object properties, and functions while introducing the iterable and iterator protocols explicitly.
What you can do after
Build it from scratch with `Symbol.iterator` and `next()`, or use a generator; customize iteration and consume infinite iterables selectively.
How it connects
Connects the iterable protocol to the iterator protocol, generators, `for..of`, spread syntax, arrays, strings, sets, and maps.

Also explained in

Compare how 7 books explain iterable →

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.