You will finally understand what Closure is

Nested functions, event handlers, ajax callbacks, encapsulation and more

Cristian Salcescu
Frontend Essentials

--

Photo by the author

Closure is a nested function that has access to the parent variables, even after the parent has executed.

Consider the following code:

function init(){
let state = 0;

function increment(){
state += 1;
return state;
}

increment();
}
init();

The function increment() is a closure.

increment() is a nested function. init() is its parent. increment() accesses the variable state from its parent.

Closure becomes important when the nested function survives the invocation of the parent.

Look at these examples:

  • Timer callback
function initTimer(){
let state = 0;

setTimeout(function increment(){
state += 1;
return state;
}, 60000);
}
initTimer();
  • Event callback
function initEvent(){
let state = 0;

$("#btn").on("click", function increment(){
state += 1;
return state;
});
}
initEvent();
  • AJAX callback

--

--