You will finally understand what Closure is
Nested functions, event handlers, ajax callbacks, encapsulation and more
Published in
3 min readMay 14, 2018
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.
- 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