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 • Edited on

5 3

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay