liveBook · Manning

Iteration result

As explained in Secrets of the JavaScript Ninja, Third Edition

An object with value and done properties describing the outcome of an iterator step.

An iterator result is the object returned by next(). Its value property carries the step’s value, while done indicates whether iteration has finished. section 8.3.1

For generators, yield produces { value, done: false }; return produces { value, done: true }. If the generator throws, the error comes from the next() call. 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
}

Repeated next() calls expose the iterator results that for…of normally handles for you. section 8.3.1

Async iterators use the same result shape, but next() returns a promise that fulfills with the result. section 8.3.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines value and done for generator yields and returns, and notes that errors escape through next().
Examples
Trace array iteration through repeated next() calls and compare yielded with returned generator results.
What you can do after
Understand iterator progress by interpreting value and done across ordinary and generator steps.
How it connects
Connects iterators and iterables with generators, yield, and async iteration.

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.