JavaScript Closures Explained with Interactive Demos

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!" 

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.

submitted by /u/sanudelhi
[link] [comments]