21
Closure Explained!
A closure is a function that makes use of variable defined in outer functions that have previously returned. What does this mean, Let's quickly look at an example.
function outer(a){
return function inner(b){
return a + b;
}
}
outer(5)(5); // 10
In the above code snippet, the function inner uses the variable "a" declared in a function named "outer," and when the function inner is called, the function outer returns the function called "inner," and this is called as a closure!
Only variables used in the inner function are stored!
Closures don't remember everything from an outer function - just the variables they require!
Closures don't remember everything from an outer function - just the variables they require!
Variables that cannot be updated externally are supported in other languages. These are referred to as private variables, although they are not included in JavaScript. No need to be concerned - closures can assist!
function counter(){
let count = 0;
return function(){
count++;
return count;
}
}
const counter1 = counter();
counter1(); // 1
counter1(); // 2
const counter2 = counter();
counter2(); // 1
counter2(); // 2
counter1(); // 3 this is unaffected by counter2.
console.log(count);
// Uncaught ReferenceError: count is not defined - because it is private!
Thank you for making it till the end!
21