Iterators in JavaScript. Code examples open

Iterators in JavaScript. Code examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: ES6

Iterators are used to organize sequential access to elements of data sets – arrays, Set, Map objects, strings, etc. So, thanks to iterators, we can iterate over a data set using a for-of loop:

    const people = ["Alexander", "Sergey", "Timote"];

    for (const person of people) {
        console.log(person);
    }

const person – a variable into which one element is written at each iteration of the loop
people – an iterable object from which we can get individual elements in the loop

But this ability to iterate over some object, such as the array in the example above, is realized due to the fact that these objects use iterators.

Iterators provide a next() method that returns an object with two properties: value and done

    {value, done}

value – the property stores the actual value of the current iterated element.
done – indicates whether there are more objects in the collection available for iteration. If there are more elements in the set, then the property
done is false.
If there are no more elements to iterate over, then this property is true.

Some types in JavaScript have methods that return iterators. For example, the entries() method of type Array (that is, arrays):

    const people = ["Alexander", "Segey", "Timote"];

    const items = people.entries();

    console.log(items.next());

In console:

    { value: Array(2), done: false }
    done: false
    value: Array(2)
    0: 0
    1: "Alexander"
    length: 2
    __proto__: Array(0)
    __proto__: Object

Here we can see that the done property is set to false because we’ve only iterated over one element.
The value property represents an array of two values. The first value represents the key or index of the array element, and the second element is the value at that index.

Accordingly, we can organize and enumerate the entire collection:

    const people = ["Alexander", "Sergey", "Timote"];
    const items = people.entries();//get an iterator

    while (!(item = items.next()).done) {
        console.log(item.value);
    }

The done property – if it is false (that is, there are still elements in the set), then we continue the loop.

[script]
console.log(item.value);
[/script]

Since each returned element represents an array, where the first element is the index in the array and the second element is the value itself, by referring to the second element we can get the value:

    while (!(item = items.next()).done) {
        console.log(item.value[1]);
    }

But that doesn’t make sense, because all collections that return iterators support iteration with a for…of loop, which is what uses the iterator to get the elements.

Different objects may have their own iterator implementation. And if necessary, we can define an object with with your iterator. The use of iterators provides us with a way to create an object that behaves like a collection of elements.

    const iterable = {
        [Symbol.iterator]() {
            return {
                next() {
                    // if there are more elements
                    return { value: ..., done: false };
                    // if there are no more elements
                    return { value: undefined, done: true };
                }
            };
        }
    };

The [Symbol.iterator]() method returns an object that has a next() method. This method returns an object with two properties value and done.

If our object has elements, then the value property contains the actual value of the element, and the done property is false.

If there are no more elements available, then the done property is true.

For example, let’s implement the simplest object with an iterator that returns some set of numbers:

    const iterable = {
        [Symbol.iterator]() {
            return {
                current: 1,
                end: 3,
                next() {
                    if (this.current <= this.end) {
                        return { value: this.current++, done: false };//increment by 1 on each call
                    }
                    return { done: true };//if the limit is reached and the number is greater than 3
                }
            };
        }
    };

Get the elements it returns from the iterator:

    const myIterator = iterable[Symbol.iterator](); //get an iterator
    console.log(myIterator.next()); // {value: 1, done: false}
    console.log(myIterator.next()); // {value: 2, done: false}
    console.log(myIterator.next()); // {value: 3, done: false}
    console.log(myIterator.next()); // {done: true}

It can be iterated with a for-of loop:

    const iterable = {
        [Symbol.iterator]() {
            return {
                current: 1,
                end: 3,
                next() {
                    if (this.current <= this.end) {
                        return { value: this.current++, done: false };
                    }
                    return { done: true };
                }
            };
        }
    };
    for (const value of iterable) {
        console.log(value);// 1 2 3
    }

The for-of loop automatically calls the next() method and retrieves the value.

Loops in JavaScript. Code examples open
Loops in JavaScript. Code examples
July 24, 2022
Roman-tk

Let’s look at another example:

    const team = {
        [Symbol.iterator]() {
            return {
                index: 0,
                members: ["Alexander", "Sergey", "Timote"],
                next() {
                    if (this.index < this.members.length) {
                        return { value: this.members[this.index++], done: false };
                    }
                    return { done: true };
                }
            };
        }
    };
    for (const member of team) {
        console.log(member);
    }
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2025
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation