Javascript Closures the easy way

aspiiire

Aspiiire

Posted on June 15, 2021

Javascript Closures the easy way

Closures in javascript seems a hard topic as it is portrayed by the majority of people, in this simple explanation i will break it down and show you that in reality it is not.

Let's start with a simple well known example:

function createCounter(){
    var i = 0;
    return function(){
        console.log(i++);
    }
}

var x = createCounter();
Enter fullscreen mode Exit fullscreen mode

In this example i firstly have defined a function createCounter that contains a var definition i initialized to 0 then i return an anonymous function.

Inside this function i simply increment the value of i.

At the end i have defined the variable x that once executed it will contain the returned anonymous function, to clarify it will contain something like this:

function(){
    console.log(i++);
}
Enter fullscreen mode Exit fullscreen mode

I said "something like this" because it will not only contain the function seen before but it will enclose the i variable, what i mean is that this function will have a reference to the outer scope's previously defined i variable.

Now... What happens when we execute the x variable? It prints out the value 0, 1, 2, 3.... but the strange thing is that it remembers the state of the i variable and it increments it, well, this feature it's the so called closure.

You have access from your function to the outer scope to a reference of i, if you see the definition given in the Javascript MDN you will see that fits in perfectly:

Another example

Let's do another example, this time i will add a new little little difference:

function createCounter(){
    var i = 0;
    var m = 5;
    return function(){
        console.log(i++);
    }
}
var x = createCounter();
Enter fullscreen mode Exit fullscreen mode

If we execute this example you will see that inside the x variable enclosed in you have only the i variable and you can't see the m variable; That means that you have only enclosed the used variables.

To try this type console.dir(x)

I hope that in this breaf explanation i have clarified a lot of misconceptions about closures.

💖 💪 🙅 🚩
aspiiire
Aspiiire

Posted on June 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related