A closure is a function that has access to the outer (parent) scope, even after the outer function has finished executing. JavaScript variables can belong to the local or global scope. Closures make it possible for a function to have "private" variables.
A function can access variables defined inside the function (local scope) or outside of it (global scope).
let a = 4; // Global
function myFunction() {
return a * a; // Can access global variable
}
Suppose you want to use a variable for counting something, and you want this counter to be available to all functions. But you also want to prevent any other code from changing the counter accidentally.
If the counter is global, any script can change it. If it is local, it resets every time the function is called. The solution is Closure.
A closure is created when an inner function is made available outside of the function in which it was defined.
const add = (function () {
let counter = 0; // "Private" variable
return function () {
counter += 1;
return counter;
}
})();
add(); // returns 1
add(); // returns 2
add(); // returns 3
add variable becomes a function.add function has access to the counter
in the parent scope. This is called a JavaScript closure.