Os desejos que desejamos pro outro

Por mais que ele mereça aprender com momentos difíceis, por mais atrapalhado que ele seja, você deseja que ele tenha sabedoria. Que ele saiba passar por esses momentos. Por mais que eu queira que os…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Iterators and Iterables in JavaScript

Iterators and Iterables in JavaScript

In computer programming, an iterator is an object that allows us to traverse through a collection in a container. This is also described as a software design pattern in GOF’s design patterns¹ book. This design pattern is named Iterator². The definition by GOF is:

JavaScript has this pattern implemented. It is such an architecture you can not think of a programming language without it. JavaScript has implemented this pattern in all collection objects and other places. Like other languages, this language has also a way to implement the iterator pattern.

ES6 actually introduces iterators in JavaScript. Iterators are very essential for efficient data processing. It makes things easier to work with collections of data. You do not need to initialize variables to track positions of elements while traversing a collection.

When using the standard for loop, you have to maintain variables to track positions for elements whether you need it or not. It increases the complexity when you work with nested for loops and when you need to keep tracking of multiple variables. This is where iterators come in handy. Because it does not need to track positions for elements. So let us go for it.

In JavaScript, iterators are also objects with a specific interface designed for iteration. All iterators have a method named next() which returns an object as a result. This result object will have two attributes named value and done.

These two attributes are populated with proper values on each call to next() method. The value and done attributes become undefined and true respectively when no more elements to return from a collection.

Let us create an iterator keeping things in mind we just learned about. We are going to use ES5. Look at code below:

Here we implemented what we learned from the definition. We put that in a function named createIterator(). We create an iterator using this function by passing some elements as an array. Then we traversed the elements using while loop with the help of the next() method of the iterator. Next, we would learn how we can make an object iterable.

Like an iterator, an iterable is also an object. An iterable object has a property named Symbol.iterator. This symbol property specifies a function that returns an iterator. Therefore, an iterable object returns an iterator. Why? We want to make an object iterable so that we can traverse through elements of an object.

In JavaScript, whatever you deal with is an object. But an object may not be iterable. When you implement iterator pattern to an object, that object then becomes iterable. Therefore, that object has then this Symbol.iterator property which represents a method that establishes iterator what we learned in the previous section.

That means they are all iterables. We can check that out. To do so, we need to create a function to check whether or not the Symbol.iterator property is in the given object:

We could access the default iterators of these built-in iterables. So we would see now how we can access next() method of an iterator. You can access the default iterator from any iterable mentioned above, but in this case, we would use an array.

So this is now clear that Symbol.iterator property specifies an iterator to an object. That means whenever we want to implement iterator pattern we can use this symbol property to make an object iterable.

So far, we have seen what iterators and iterables are, what built-in iterables are, how we can access the default iterator of an iterable. Now we would see how to iterate over the data of a collection.

At this point, we know that JavaScript has some built-in iterables. To iterate over the elements of an iterable, ES6 provides a new loop for-of loop. Iterables are designed to be worked with for-of loop. Check out below:

Let us dig into the code snippet. characters is an array here. It has a symbol property called Symbol.iterator that we saw earlier. for-of loop calls the characters array’s [Symbol.iterator]() method which returns an iterator object. This happens behind the scene.

We know that iterator has a next() method. On each iteration, for-of calls iterator.next() method and it returns an object with two properties value and done. Then the value property is read into char variable. Thus char gets new value each time the loop executes. This is very interesting, isn’t it?

It is time to create an iterable object. In JavaScript, user-defined objects are not iterables. You have to implement this pattern if you need an iterable object. Okay! we know how to do that and what needs to make an object iterable. Because we have already learned it. This is our iterable object:

Here we created the default iterator using the Symbol.iterator method which is a generator. A generator is a function that returns an iterator. This generator function uses for-of loop to iterate over elements from another iterable which is an array.

Here we used Symbol.iterator property on the collection object literal. This property used a generator to return an iterator. The whole process made the collection object iterable. That is why we have been able to traverse over the elements of the collection object.

But we could make the default iterator without a generator. Here is the implementation of an actual iterator pattern:

This should work the same way the iterator using the generator does. You can try with this one by pushing some elements into the collection.elements array. Then iterate over the elements of the collection object.

An iterable is an object with a symbol property named Symbol.iterator. This returns an iterator. An iterator has a method named next() which is called on each iteration of a loop. Both together, iterator and iterable, make an object iterable. We can use for-of loop to traverse any iterable object without tracking positions of elements from a collection or a sequence.

We have seen that iterators are used in all JavaScript collection objects. Iterator exists in a String object. It is also used in the generator function which makes it very concise than the general implementation of an iterator.

I hope you enjoyed this article. If you have any confusion with any part of this article and find any flaw please let me know via comment section. I would be with you.

Thank you very much as you are here.

Add a comment

Related posts:

Brunch Fest Toronto joins vendors from across city

Brunch Fest Toronto took over the grounds of Hotel X Toronto this past weekend, showcasing a variety of tastes from unique vendors all in one location. Hundreds of event-goers with big appetites…

The Rise in Autoimmunity

Autoimmunity is a mysterious illness that leads the immune system to overreact and begin attacking its own tissues in the absence of a foreign invader. One hypothesis is that in our over-sanitized…

Get What You Want Now

Now and then you need a kick in the ass to get it together. I talked with a friend the other day, and we agreed that we give great advice. I realize that sounds pretty shallow, but we also agreed we…