liveBook · Manning

Value property

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

The result property in an iteration result that carries the yielded or returned value associated with that step.

What does an iterator hand back each time you ask for another item? Calling next() returns an iteration result. Its value property carries the item produced on that step; its done property tells you whether iteration has finished. Keep the two together: value says what you got, while done says whether to keep asking. section 23.4

Watch a generator yield

For function* letters() { yield 'a'; yield 'b'; }, successive calls to letters().next() produce { value: 'a', done: false }, then { value: 'b', done: false }, then { value: undefined, done: true }. Each yield supplies an outgoing value and pauses execution. Reaching the end instead finishes the generator. If it explicitly returns a value, that final result can have done: true and a value other than undefined. section 18.2 section 18.1

Don’t confuse the value property with an argument passed to next(). A yielded value travels out in the result object; a later next(argument) can send a value back into the paused generator. The argument to the very first next() is not received by a yield, because that call only starts execution. section 18.2 section 18.1

function primesIterator () {
  const primes = [2, 3, 5]
  return {
    next() {
      const value = primes.shift()
      const done = !value
      return {
        value,
        done
      }
    }
  }
}

This hand-written prime-number iterator takes an item from an array and returns it as value alongside done. Once the items are exhausted, done tells callers to stop. section 23.4

Try calling next() yourself on a generator that yields two values, then reaches its end. Check both properties after every call. When you use spread or for..of instead, they repeatedly request iterator results and stop when done becomes true. section 18.2 section 23.4

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

How deep it goes
Defines value within iteration results and works through yielded, completed, and manually produced results.
Examples
Uses generator results containing 'a' and 'b' and an iterator producing the first three prime numbers.
What it assumes
Assumes familiarity with JavaScript functions and objects while defining iterators and generator behavior through examples.
What you can do after
Build it from scratch by returning value and done from next(), or inspect generator results one call at a time.
How it connects
Connects value to the iterator protocol, generators, yield, done, spread, and 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.