in , ,

JavaScript Iterators and Iterables

JavaScript Iterators and Iterables
JavaScript Iterators and Iterables

In this tutorial, you will learn about JavaScript iterators and iterables with the assistance of examples.

Introduction to Iterables and Iterators in JavaScript

JavaScript supports a protocol by which objects, for example, arrays can be used by control constructions, for example, for… of and the spread operator … to loop through data successively. This is alluded to as the iterable and the data structures that support this usefulness are called iterable. While JavaScript gives maps, arrays, and sets with an iterable property as it so happens, plain objects don’t have this by default.

Iterables are data structures that give a mechanism to allow other data customers to publicly get to its components in a successive way. Envision a self-package data structure that unloads data individually all together when put within a for…of loop.

The concept of the iterable protocol can be part into the iterable (the data structure itself) and the iterator (sort of a pointer that moves over the iterable). How about we think about an array for instance when the array is used in a for…of loop, the iterable property is called which returns an iterator. This iterable property is namespaced as Symbol.iterator and the object that it returns can be used for a typical interface that is shared by all looping control structures.

As it were, the Symbol.iterator can be contrasted with an iterator industrial facility that delivers an iterator at whatever point the data structure is put in a loop.

As an iterator moves over the data structure and gives the components consecutively, the object returned by the iterable contains a value and a done property.

The value shows the current data value pointed by the iterator and done is a boolean that tells us if the iterator has arrived at the last component in the data structure.

This {value, done} is devoured by constructions, for example, loops. So how does the iterator strategy call the next object? Using a next() strategy that is characterized inside the Symbol.iterator() technique.

A better definition for the iterator property that I can accompany now is that it’s a property that realizes how to get to components from an assortment individually and furthermore, provides a logical rule to quit doing as such (eg. in the event that there are no more elements in the array).

JavaScript Iterables and Iterators

JavaScript provides a protocol to iterate over data structures. This protocol characterizes how these data structures are iterated over using the for…of loop.

The concept of the protocol can be part into:

  • iterable
  • iterator

The iterable protocol specifies that an iterable ought to have the Symbol.iterator key.

JavaScript Iterables

The data structures that have the Symbol.iterator() technique are called iterables. For instance, Arrays, Strings, Sets, and so forth

JavaScript Iterators

An iterator is an object that is returned by the Symbol.iterator() strategy.

The iterator protocol gives the next() strategy to get to each component of the iterable (data structure) each in turn.


Let’s look at an example of iterables having Symbol.Iterator()

const arr = [1, 2 ,3];

// calling the Symbol.iterator() method
const arrIterator = arr[Symbol.iterator]();

// gives Array Iterator
console.log(arrIterator);

const str = 'hello';

// calling the Symbol.iterator() method
const strIterator = str[Symbol.iterator]();

// gives String Iterator
console.log(strIterator);

Output

Array Iterator {}
StringIterator {}

Here, calling the Symbol.iterator() technique for both the array and string returns their respective iterators.


Iterate Through Iterables

You can use the for…of loop to iterate through these iterable objects. You can iterate through the Symbol.iterator() technique like this:

const number = [ 1, 2, 3];

for (let n of  number[Symbol.iterator]()) {
    console.log(n);
}

Output

1
2
3

Or on the other hand, you can essentially iterate through the array this way:

const number = [ 1, 2, 3];

for (let n of  number) {
    console.log(n);
}

Here, the iterator allows the for…of loop to iterate over an array and return each worth.


JavaScript next() Method

The iterator object has a next() strategy that returns the next item in the arrangement.

The next() technique contains two properties: value and done.

  • value

The value property can be of any data type and addresses the current value in the arrangement.

  • done

The done property is a boolean worth that shows whether the iteration is complete or not. On the off chance that the iteration is incomplete, the done property is set to false, else it is set to valid.

Let’s look at an example of array iterables:

const arr = ['h', 'e', 'l', 'l', 'o'];

let arrIterator = arr[Symbol.iterator]();

console.log(arrIterator.next()); // {value: "h", done: false}
console.log(arrIterator.next()); // {value: "e", done: false}
console.log(arrIterator.next()); // {value: "l", done: false}
console.log(arrIterator.next()); // {value: "l", done: false}
console.log(arrIterator.next()); // {value: "o", done: false}
console.log(arrIterator.next()); // {value: undefined, done: true}

You can call next() repeatedly to iterate over an arrIterator object.

  • The next() method returns an object with two properties: value and done.
  • When the next() method reaches the end of the sequence, then the done property is set to false.

Let’s look at how for…of loop executes the above program. For instance,

const arr = ['h', 'e', 'l', 'l', 'o'];

for (let i of arr) {
    console.log(i);
}

Output

h
e
l
l
o

The for…of loop does exactly the same as the program above.

The for…of loop keeps calling the next() method on the iterator. Once it reaches done:true, the for…of loop terminates.


User Defined Iterator

You can likewise make your own iterator and call next() to get to the next component. For instance,

function displayElements(arr) {

    // to update the iteration
    let n = 0;

    return {

        // implementing the next() function
        next() {

            if(n < arr.length) {
                return {
                    value: arr[n++],
                    done: false
                }
            }

            return {
                value: undefined,
                done: true
            }
        }
    }
}

const arr = ['h', 'e', 'l', 'l', 'o'];

const arrIterator = displayElements(arr);

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

Output

{value: "h", done: false}
{value: "e", done: false}
{value: "l", done: false}
{value: "l", done: false}
{value: "o", done: false}
{value: undefined, done: true}

In the above program, we have made our own iterator. The displayElements() work returns value and done property.

  • Each time the next() technique is called, the function gets executed once and showcases the value of an array.
  • At long last, when all the components of an array are exhausted, the done property is set to valid, with value as undefined.

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

JavaScript "use strict"

JavaScript “use strict”

JavaScript Generators

JavaScript Generators