Daniel Bark

← Back to blog

Published 2020-08-27 by Daniel Bark

0
0

Making your own Javascript Iterator

Probably many Javascript developers first stumble upon Iterators when looking into the for…of loop. The for…of statement creates a loop and needs an iterable object in order to do so.

So what are iterable objects in Javascript?

Yeah you guessed it. Arrays is one. We also have some array-like objects such as arguments and NodeLists. Maps, Sets and TypedArrays are also iterable objects. The last honorable mention is the String.

When we iterate these objects an iteration hook with statements are executed for the value of each distinct property of the object.

With this knowledge, could we add a custom iteration hook for a plain Javascript Object which is not iterable by default? A rhetorical question of course.

Symbol.iterator

There is a default iterator available to us in Symbol.iterator.
Lets first see what happens if we remove that from a normal Array.

Now lets try adding it to a plain Object.

Ok there are a few things to unpack here. We are creating an iterator on the object which is a function that creates an array of the objects values and calls the iterator of that array. If we want to format the output in a different way we can.

Now we are instead using the keys to create mini-objects per property.

But this is not good enough right?

Let’s iterate

The title talks about making your own Iterator. Here we go…

An iterator needs to implement a next() function that returns an object with the properties done and value.

We have two outcomes of our next function. Either done is false and value is the current Object entry, or done is true and value is undefined.

Lets slap this function onto a plain object and try it out.

Pretty cool stuff.

I hope you found this article interesting and that you learned something new about Javascript.

I would be happy if you stopped by my Youtube channel: @danielbark

Written by Daniel Bark

← Back to blog