Closure
JavaScript variables can belong to:
- The local scope
- The global scope
Global variables can be made local (private) with closures.Closures make it possible for a function to have "private" variables.A closure is created when a function remembers the variables from its outer scope, even after the outer function has finished executing.
Example:
Suppose you want to use a variable for counting something, and you want this counter to be available to everyone (all functions).You could use a global variable, and a function to increase the counter:
// Initiate counter
let counter = 0;
// Function to increment counter
function add() {
counter += 1;
return counter;
}
// Call add() 6 times
console.log(add());//1
console.log(add());//2
console.log(add());//3
console.log(add());//4
console.log(add());//5
console.log(add());//6
Warning !
There is a problem with the solution above: Any code on the page can change the counter, without calling add().
counter =100;
add();
console.log(counter);//100
console.log(add);//102
The counter should be local to the add() function, to prevent other code from changing it.They want counter should be hidden from outside the world.Like this:
function add() {
let counter = 0;
counter += 1;
return counter;
}
// Call add() 6 times
console.log(add());//1
console.log(add());//1
console.log(add());//1
console.log(add());//1
console.log(add());//1
console.log(add());//1
But this is not we want .It did not work because we reset the local counter every time we call the function.Because every time the function runs ,creates a new variable.The solution is We need a closure.
function myCounter() {
let counter = 0;//variable in outer function
function inner() {
counter++;//inner function uses other variable
console.log(counter);
}
return inner;
}
const add = myCounter();
add();//1
add();//2
add();//3
const adding = myCounter();
adding();//1
adding();//2
add();//4
Eventhough, the outer function has finished, the inner function remembers the count. This is called closure.
Reference
https://www.w3schools.com/js/js_function_closures.asp
Top comments (2)
This is a great intro! I often explain closures by
Thank you