DEV Community

Cover image for How to for..of with your own objects in JS (iterable & iterator protocol) [LET'S CODE]
crayoncode
crayoncode

Posted on • Updated on

How to for..of with your own objects in JS (iterable & iterator protocol) [LET'S CODE]

Generally and theoretically an iterator is an object that produces a sequence of values. Practically, an iterator can be used to loop over the items of a list. If we put both together, you could say that it reproduces the list's sequence of items. And that's exactly what we're going to do with the doubly linked list from last time. Watch this episode of crayoncode and let's write some code together! ⌨️📐⚙️

There are two important protocols that make for...of work: One is called iterable and the other is called iterator.

The iterable protocol states, that an iterable object must have a function which is accessible through Symbol.iterator. This function does not take any parameters and returns a so-called iterator.

An object is considered an iterator if it has a function called next. It also does not take any parameters and each time it's called, it must return an object of defined structure:

  • The value property represents the current iteration's value, i.e. the element in the iterable structure (e.g. a list) the iterator is currently on.
  • The done property tells the caller of the iterator if the iterator has reached the end of the iterable structure. If it is true, the value property can be omittted.

So, both of these protocols work closely together during the evaluation of a for...of loop.

Top comments (0)