DEV Community

machy44
machy44

Posted on • Updated on

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 :)

Top comments (0)