Having defined in the previous part what the Lexical Scope is, it is time now to see what is the concept of Closure and why there is a huge fuzziness around it.
Googling “What is closure in Javascript”, one will find the answer:
“A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment)”.
But this definition, only brings more confusion rather clarification. Let’s try to understand closure by reviewing the following snippet.
function whatIsClosure( ) {
const a = 5;
function printInConsole( ) {
console.log(a);
};
return printInConsole;
};
const showMeClosure = whatIsClosure();
showMeClosure();
This code, will print in the console the value 5. But how did we manage to access the function printInConsole outside of its declared lexical scope?
Let’s try to understand what is happening in this code. The function printInConsole has lexical scope access to the whatIsClosure’s scope. This is how the Javascript Engine will find the variable a and see what value it has being assigned to. Then, our main function, simply returns printInConsole, but as a value now. Then, the result of our main function is being assigned to the variable showMeClosure. But when we call our variable, which is a function, which function returns another function’s result, it is the same as we would have called printInClosure itself. Thus, we see that our nested function still has access to the main function, even when we execute it outside of its lexical scope. Therefore, printInConsole “closes” (memorizes) the variable a from its lexical scope, or in other words, printInConsole is a Closure since it can “capture” variables from its lexical scope.