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)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.