The best analogy to understand closures is Backpack.
Read More, Check out the interactive demo here
function exFunctionA() { const outerVariable = "I'm from the outside!"; function exFunctionB() { console.log(outerVariable); // Accesses the variable from its "backpack" } return exFunctionB; } const myClosure = exFunctionA(); // outerFunction runs and is gone... myClosure(); //...but innerFunction still has its backpack! Logs "I'm from the outside!"
- Think when we define any function (Function A), we define some variables inside it (lexical scope). Here we define the variable outerVariable inside Function A.
- Think, to remember this information, functions create a backpack and hold all these values inside it.
- Then again we define another function (Function B) inside our parent function (Function A). The Function B has access to the variable defined in the parent function (Function A).
- So now our inner function will create a backpack and hold all this information. When our outer function (Function A) executes and returns its context and lexical scope also finishes. But remember our inner function (Function B) has its own backpack, and inside the backpack it has the variable from the parent Function A (which is already executed).
Now this phenomena, after the execution of parent Function A and lapsing of its lexical scope. Our inner Function B can still access the variable which was defined inside the parent Function A is called Closures.