AppDividend
Latest Code Tutorials

Javascript Iterators Example | ES6 Iterables And Iterators

0

Javascript iterators is a new concept of ES6 in which it processes each of the items in the collection, which is 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.

Iterators in  Javascript

Content Overview

An iterator is a new concept of ES6. An Iterator 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 in their entirety, 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, then 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 iterator. 

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

Further, iterator in javascript also returns the object, which we store in a variable. Then when we logged 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, then the last object has the value undefined and done 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 that whether the next value is there or not, so it gives the done = false. 

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

How can we define the iterators?

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 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 their behavior. For example, arrays are not iterators in ES6
  3. An Iterator lets us iterate the content of an object at a given point of 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 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

With the knowledge gained from the article, you can easily understand how the iterator is working. The logic may be a bit hard to follow.

Finally, Javascript Iterators Example | ES6 Iterables And Iterators Tutorial are over.

Leave A Reply

Your email address will not be published.

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