Simplifying the magic of JavaScript closures with example

Closure is an advanced JavaScript concept that many developers find hard to understand. This concept feels confusing because it challenges our general understanding that an execution context and all the variables within it are removed once the execution is complete.

While this is generally true, it doesn't apply to closure. In JavaScript, closure is created for every function, allowing a function to retain access to all the variables it uses from its parent contexts, though the parent contexts have returned and finished their execution.

Let's understand this definition with an example:

function counter() {
  let count = 0;

  return function increment() {
    count++;
    console.log(count);
  };
}

const increment = counter();
increment(); // 1

In the above code, we have a function called counter that contains a count variable and returns another function called increment. Within the increment function, we increment the count variable and log it to the console.

Moving on in the code, we call the counter function and store its results in the increment variable. The increment variable now holds the increment function returned by the counter function.

Finally, we call the increment function, which increments the count variable and logs it to the console. It's worth noting that these actions of accessing and modifying the count variable within the increment function are made possible because of closure.

In the JavaScript code execution process, when the increment function is executed, the counter function has already completed its execution and been removed from the call stack. This should remove the count variable as well, making it inaccessible within the increment function, right?

Well, that's not the case here. Due to the closure of the increment function, it retains access to the count variable from the counter function, though the counter function has already finished its execution. This is how closure works.

Good to know that the JavaScript engine keeps a variable in memory as long as it is used somewhere in the code, though the context of the variable has already been executed.

That's the essence of closure and how it works in JavaScript. I hope you've learned a thing or two about this advanced JavaScript concept from this article. Happy learning!

Share this article with your friends

Copy URL

Elevate your JavaScript and freelance journey

Supercharge your JavaScript skills and freelance career. Subscribe now for expert tips and insights!