- In JS, functions are objects and can be declared anywhere.
- If I declare a function within another function, the inner function has access to the local variable of the outer function.
- Normally, when a function exists only the return portion is not cleared from memory.
- But if I can hang on to the inner function, the local variables of the outer variables still need to be referenced by the inner function because of the concept of scope. Scope answers the question, “Where are my variables and functions available to me?”
- Because the value is still in scope, we can keep a persistent memory of what is called closure.
Closure is powerful because it allows us to build functions that allow us to remember some of their previous execution “memories.” We gain a live store of data (local memory/variable environment/state) for that function’s execution context. You can’t access this closure data from console.log(); it is only accessible from scope from an inner function not finding a variable and then moving up to the outer function to find the data.
Closure serves as the gateway between the global execution context and the outer scope. Closure is created at every function call.