A JavaScript closure is formed when you define a function within a function. The inner function will remember the variables of the outer function, which encloses it, even after the outer function has finished executing.
Here's an example:
function outerFunction() {
const outerFunctionVariable = `the outer function's data`;
const innerFunction = function() {
console.log(`I remember ${outerFunctionVariable}!`);
}
return innerFunction;
}
const closureFunction = outerFunction();
closureFunction();
Output:
I remember the outer function's data!
As you can see above, outerFunction was invoked, and returned innerFunction, which was stored in closureFunction.
Then, closureFunction was invoked, which referenced innerFunction, and printed the data from outerFunction.
innerFunction remembered the variable of the outerFunction even after outerFunction was finished executing.
Apparently, there are many use cases for JavaScript closures, which we'll cover in the next webLog.
Some use cases are:
See you next time!