Closure#

The cleanest and best explanation of javascript closures.

This is from 5 Advanced JavaScript Techniques You Should Know

Closure#

Closure is an important technique in Javascript. It means that an inner function always has access to the variables and parameters of its outer function, even after the outer function has returned. We use closure to protect data that we don’t want to expose to the outer scope. Let’s say you want to increase a counter variable one unit every time a button is clicked. Something like:

<button onclick=increaseCounter()>Increase Counter</button>

Simply, we can use a global to finish the task:

let counter = 0;
function increaseCounter() {
  counter++;
}

The problem is that the the counter variable can be change directly without calling increaseCounter() function. So, let’s move the counter variable into the function:

function increaseCounter() {
  let counter = 0;
  counter++;
}

Nah, the counter variable will be reset to 0 every time the function is called. It’s when closure comes into play:

const increaseCounter = (function() {
  let counter = 0;

  return function() {
    counter = counter + 1;
    console.log(counter);
  };
})();

The IIFE run only once and initialize the counter variable with 0 then returns a function that can access the counter variable. So, when you call increaseCounter(), it will update the counter as expected.