JavaScript Iterators: The Complete Guide

Javascript iterators is a new concept of ES6 in which it processes each of the items in the collection, a pervasive operation. Iterators are a new way to loop over any collection in JavaScript.

They were introduced in ES6 and have become popular since they are widely JavaScript provides several ways of iterating over the collection, from simple for loops to map() and filter() Iterators and Generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of loops.

JavaScript Iterator

An iterator in JavaScript is an object that lets us iterate through an Arrayan ObjectString, or even custom Objects. The Iterator allows us to effectively loop over a collection of objects like an array, string, objects, or other data structures.

The most common iterator in JavaScript is the Array iterator, which returns each value in the associated array in sequence.

While it is easy to imagine that all iterators could be expressed as arrays, this is not true.

Arrays must be allocated entirely, but iterators are consumed only as necessary and thus can express sequences of unlimited sizes, such as the range of integers between 0 and Infinity.

Example

//main.js

let dances = ['Robot', 'Hip-hop','break'];
let mj = dances[Symbol.iterator]();
console.log(mj.next());

If you are directly running the above code in the browser, you might face the following issue.

Possible Errors

  1. You can get any syntax errors.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put the above code in the main.js file.

Output

Object {value: "Robot", done: false}

Weird right? However, that is the meaning of the Iterator

It provides an interface we can call the method like next(). 

Further, the Iterator in javascript also returns the object we store in a variable. Then when we log it into the browser, we can see an object with the two properties

  1. value: It holds the next value of an iterator object.
  2. done: It is the flag that indicates that the items in the iterable object are not complete in the iterating process.
//main.js

let dances = ['Robot', 'Hip-hop','break'];
let mj = dances[Symbol.iterator]();
console.log(mj.next().value);

Output

Robot
//main.js

let dances = ['Robot', 'Hip-hop','break'];
let mj = dances[Symbol.iterator]();
console.log(mj.next().done);

Output

false
//main.js

let dances = ['Robot', 'Hip-hop','break'];
let mj = dances[Symbol.iterator]();
console.log(mj.next());
console.log(mj.next());
console.log(mj.next());
console.log(mj.next());

Output

Object {value: "Robot", done: false}
Object {value: "Hip-hop", done: false}
Object {value: "break", done: false}
Object {value: undefined, done: true}

If you notice carefully, the last object has the value undefined, which is true. It means that our array has only three items, and up to 3 items done is false because the compiler does not know whether the next value is there, so it gives the done = false. 

After that, when the next value is not there, it will give the value = undefined and done = true.

How can we define the iterators?

For an object or an array to be iterable, it needs to implement the iterable protocol, meaning that the object must have a property with a Symbol.iterator key. In the previous example, we have used this protocol.

//main.js

let mj = dances[Symbol.iterator]();

We have used dances array, and to make it iterable, we have used Symbol. iterator protocol to make it iterable.

We can test the variable, whether it is an array or an object that is iterable or not, by the following code.

//main.js

function itemIterable(item) {
    return typeof item[Symbol.iterator] == "function";
}

In the above example, when we pass the mj array to this itemIterable() function, we will get the following result.

//main.js

let dances = ['Robot', 'Hip-hop','break'];
let mj = dances[Symbol.iterator]();
function itemIterable(item) {
    return typeof item[Symbol.iterator] == "function";
}
let result = itemIterable(mj);
console.log(result);

Output

true

Javascript for loop

It creates a loop iterating over iterable objects like an array, object, map, set, weak set, string, and its new feature of ES6.

Syntax

for (var of iterable) {
  // statement
}

var: On every iteration of the loop, a value of a different property is assigned to the variable.

iterable: An object whose properties are iterated.

//main.js

let dances = ['Robot', 'Hip-hop','break'];
for (let value of dances){
    console.log(value);
}

Output

Robot
Hip-hop
break
Iterators in Javascript
Iterators in Javascript

If we want to create an iterator, then first take an object and then add Symbol.iterator protocol in it so it returns an interface in which we can call the next() method, and then finally, we get an object, which has 2 properties value and done.

Key Points of Iterators

  1. Iterators are functions that provide an interface through which we can call the method like next() and, in return, gives us an object.
  2. Iterators are created using the iterable protocol that allows the iterable object to customize its behavior. For example, arrays are not iterators in ES6.
  3. An Iterator lets us iterate an object’s content at a given time.
  4. An Iterator creates Traversable Data Structures.

Javascript Iterables

An iterable is a data structure that wants to make its elements accessible to the public. It does so by implementing a method whose key is Symbol. Iterator. That method is a factory for iterators. That is, it will create iterators.

An iterator is a pointer for traversing the elements of a data structure.

A lot of things are iterables in JavaScript. It may not be visible immediately, but if you examine it carefully, iterables will start to show.

These are all iterables —

  • Arrays and TypedArrays
  • Strings — iterate over each character or Unicode code-points.
  • Maps — iterates over its key-value pairs
  • Sets — iterates over their elements
  • arguments — An array-like particular variable in functions
  • DOM elements (Work in Progress)

Conclusion

You can easily understand how the Iterator works with the knowledge gained from the article. However, the logic may be a bit hard to follow.

That’s it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.