What are Iterators in JavaScript

JavaScript offers several ways to iterate through a collection of object values such as loops.  However, Iterators are introduced in JavaScript 1.7, which provides a mechanism to customize the behavior of for each and for..in loops and integrates the concept of iteration into the core language.

If you need to add native iterative functionality to a well-encapsulated and custom data structure, you should use JavaScript Iterators. It can be considered a more elegant way to standardize your custom objects.

This write-up will discuss iterators in JavaScript. We will also demonstrate the usage of iterators, iterables, next() method, and User-Defined Iterators. So, let’s start!

Iteration in JavaScript

In JavaScript, Iteration is a procedure in which a collection of structures or instructions is repeated in a sequence for a predetermined number of times or until the added condition is true. You can utilize loops for iterating over the specified set of instructions.

For instance, we have declared an array “counting” and with the help of the “for..of” loop, we will iterate over the specified array:

const counting = [ 1, 2, 3];
for (let x of counting) {
    console.log(x);
}

As a result of it, each value will be returned and shown as output:

Now, let’s check out the method for iterating over a JavaScript object. For this purpose, firstly, we will declare an object named “employee” and then utilize  for..of loop for iterating over its properties:

const employee = { name: 'Alex', designation: 'Manager' };
for (const prop of employee) {
console.log(prop);
}

As you can see, the output of the above-given code displayed a “TypeError” message which states that the “employee” object is not iterable. Why does it happen? We have encountered the TypeError because the for..of loop requires an iterable object for iterating over the object’s properties.

To handle the current situation, you can use the JavaScript Iteration Protocol, which will assist you in making an object iterable for iterating over its properties.

JavaScript Iteration Protocol

JavaScript provides an Iteration protocol for iterating over objects. This protocol specifies the procedure of iteration using “for..of” loop. JavaScript iterators are divided into two components: “Iterables” and “Iterators”:

  • Iterables: Iterables are the objects that implement the “iterator()” iteration method i.e. array or string.
  • Iterators: The object returned by the “iterator()” method is known as “Iterator“. After getting the iterator, you can use the “next()” method for sequentially accessing iterable elements.

It can be hard for you to understand the usage of these methods at a glance, so we will sequentially go through each of them in the below-given sections.

next() method in JavaScript

next()” is an iterator object method that is invoked for returning the next value in the iteration sequence. This method comprises the following two properties:

  • The “value” property represents the current value in the iteration sequence, and it can be of any data type.
  • The “done” property is used to represent the iteration status, where “false” means that the iteration is not complete and “true” indicates that the iteration process is completed.

Let’s define a custom iterator in JavaScript and access the elements of an array sequentially using next() method.

Creating User-Defined Iterator in JavaScript

JavaScript allows you to create a user-defined iterator and invoke the “next()” method for accessing the elements of the iterable object.

Here, we have defined the “showElement()” method and it will return the “value” and “done” property of the iterable object that is accepted as an argument:

function showElements(arr) {
    let number = 0;
    return {
        next() {
            if(number < array.length) {
                return {
                    value: array[number++],
                    done: false}
            }
            return {
                value: undefined,
                done: true}
        }
    }
}

In the next step, we will create an “array” and then pass it to the “showElement()” method as an argument. Then, the “showElements()” method will return an iterable object, to which we will store in “arrIterator”:

const array = ['l', 'i', 'n', 'u', 'x'];
const arrIterator = showElements(array);

Now, each time when the “next()” method is invoked with the “arrIterator”, it will display the values of array element in a sequence with the defined “value” and “done” properties:

console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());

When all of the elements are iterated, the “value” property value will be set to “undefined”, with “done” property as “true”:

The above-given output signifies that we have successfully created and executed a user-defined iterator in our program using next() method. Now, let’s understand the concept of iterables as well and have a clear and profound understanding of Symbol.iterator() in JavaScript

Example: Creating Iterators from iterables using Symbol.iterator() method in JavaScript
In this example, firstly, we will declare an array with the following three values:

const arr1 = ['l', 'i', 'n', 'u', 'x'];

Then, we will invoke the “Symbol.iterator()” method which will return an iterable object and “arrIterator” will store its value:

const arrIterator = arr1[Symbol.iterator]();
console.log(arrIterator);

Execution of the above-given program will output the array iterators:

Example: Using next() method over an iterable object in JavaScript
This example will demonstrate the usage of “next()” method for iterating over an iterable object. To do so, firstly, we will create an “array” and then invoke the “Symbol.iterator()” method for returning an iterable object:

const array = ['l', 'i', 'n', 'u', 'x'];
let arrIterator = array[Symbol.iterator]();

Invoking the “next()” will also return an object having “value” and “done” property values:

console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());

At the end of the iteration sequence, the “done” property of the “next()” method is set to “false”:

Example: Iterating through Iterables with while loop  in JavaScript
The symbol.iterator() method is automatically called by the for..of loop. If you want to invoke it manually, you can use the “while” loop for iterating over the specified iterable object.

For instance, in the below-given example, we will use the “while” loop for iterating over the iterable objects returned by the “Symbol.iterator()” method:

const array = ['l', 'i', 'n', 'u', 'x'];
let arrIterator = array[Symbol.iterator]();
let text = ""
while (true) {
  const result = arrIterator.next();
  if (result.done) break;
  console.log("value: "+ result.value + " done: " + result.done);
}

Here, the output shows the returned result with “value” and “done” iterator properties:

Look at the following diagram to understand the relationship between iterables, next() method, and iterators in JavaScript:

That was all about the basic usage of Iterators in JavaScript. You can explore it further according to your preferences.

Conclusion

Iterators in JavaScript are utilized for looping over a sequence of object values returned by the Symbol.Iterator() method. This process also involves the implementation of the next() method that returns an object with the value and done properties, where “value” represents the current sequence value and “done” determines if the iteration is completed or not. This write-up discussed JavaScript Iterators with the help of suitable examples.



from https://ift.tt/dvCxG3O

Post a Comment

0 Comments