0

Goal: Understand what this passage from "You Don't Know JS" means exactly and what JS is doing when you create an iterator.

Quoted Passage (Get Started - Chaper 3):

https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/get-started/ch3.md

"You may have noticed a nuanced shift that occurred in this discussion. We started by talking about consuming iterators, but then switched to talking about iterating over iterables. The iteration-consumption protocol expects an iterable, but the reason we can provide a direct iterator is that an iterator is just an iterable of itself! When creating an iterator instance from an existing iterator, the iterator itself is returned."

I tried to write-up what my understanding of this passage is, but in truth it just doesn't make sense to me. Questions:

  1. Are we returning an instance of an iterator from a prototype/class iterator or are is the prototype/class itself used?
  2. What does an "iterable of itself" even mean?
  3. Is an iterator declared and instantiated by let i = 0; i < ...? and referenced by the i or is it something more behind the scenes?
  • An *iterator* is an object. That `for` loop snippet in your question is **not** an iterator; it's just a loop header. An Array is an iterator, a Set, a Map, etc, and the value returned from the initial call to a generator function. – Pointy May 24 '20 at 15:25
  • 1
    I can't make sense of your first question. What do you mean by "returning from a prototype/class iterator"? – Bergi May 24 '20 at 15:28
  • "*Is an iterator declared and instantiated by `let i = 0; i < ...`?*" - No. Only `for … of` loops make use of iterators. – Bergi May 24 '20 at 15:28
  • Have a look at https://stackoverflow.com/questions/59458257/in-javascript-es6-what-is-the-difference-between-an-iterable-and-iterator – Bergi May 24 '20 at 15:41
  • @Pointy isn't an iterable an object that can be iterated over (e.g. an array, set, map, or string) but an iterator is the thing doing the iteration and separate from those? Or is this maybe where my confusion comes in? – KamiFightingSpirit May 24 '20 at 15:43
  • well right, an iterable object provides an iterator when you use it in a certain context (or in the case of a generator function, if you simply call it). It's not super-common to *directly* use the little object with `.next()` but it's certainly possible and sometimes extremely powerful and useful. I'm not 100% sure I understand what it is exactly that you're trying to figure out. – Pointy May 24 '20 at 15:47
  • @KamiFightingSpirit "*separate from those*" - yes, conceptually. But most [iterator objects are also iterable](https://stackoverflow.com/a/59458311/1048572), so that they can be iterated by a `for … of` loop. That's what the quoted paragraph is talking about. – Bergi May 24 '20 at 15:53

0 Answers0