DEV Community

Aspiiire
Aspiiire

Posted on • Originally published at priiimo.com

1 1

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.

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

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay