liveBook · Manning

Next

As explained in Secrets of the JavaScript Ninja, Third Edition

An iterator method that advances iteration and returns an iterator result.

Calling an iterator’s next() method advances it and returns an iterator result with value and done properties. On a generator, each call runs until the generator yields or returns; an uncaught error is thrown from the call. section 8.3.2 section 8.3.1

Read the result according to how iteration proceeds:

  • After yield, value holds the yielded value and done is false. section 8.3.2
  • After return or reaching the end, done is true and value holds the return value, or undefined. section 8.3.2
Listing 8.9 Looping through an array using its iterator
const numbers = [1, 2, 3];
const iterator = numbers[Symbol.iterator](); #A

let iteratorResult = iterator.next(); #B
while (!iteratorResult.done) { #C
  console.log(iteratorResult.value); #D
  iteratorResult = iterator.next(); #E
}

An array iterator makes the protocol visible: call next(), use value while done is false, then call next() again. section 8.3.1

Generator calls can also pass a value back into a suspended generator: the argument to a later next() call becomes the value of the preceding yield expression. section 8.3.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines iterator results and explains generator execution through yield, return, and thrown errors.
Examples
Uses a manually advanced array iterator and a generator that yields random numbers.
What it assumes
Introduces the iterator protocol through Symbol.iterator and iterator results before explaining generator next().
What you can do after
Operate an iterator manually by calling next() and checking done before using value.
How it connects
Connects next() to iterators, Symbol.iterator, generators, yield, and for...of loops.

Also explained in

Compare how 6 books explain next →

Related concepts

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