DEV Community

machy44
machy44

Posted on • Edited on

12 4

Understand Iterators in js

Iterators work because of closures in javascript. The iterator can be written as a function inside a function which you can see in the next code example.

function createFunction(array) {
    let i = 0;
    function inner(){
        const element = array[i];
        i++;
        return element;
    }

    return inner;
}

const returnNextElement = createFunction([4,5,6])
const element1 = returnNextElement()
const element2 = returnNextElement()

But we know that we need to use .next() property to get next element from the array. We can do that in the way that inner function becomes method.

function createFlow(array) {
    let i = 0;
    const inner = {
    next: function(){
            const element = array[i];
            i++;
            return element;
        }
    }
    return inner;
}

const returnNextElement = createFlow([4,5,6]);
const element1 = returnNextElement.next(); // 4
const element2 = returnNextElement.next(); // 5

Short and sweet :)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay