The Power Of Closure

I feel like closure is one of the most difficult things to understand in Javascript. Let’s try to break this down into a more digestible concept.

  1. In JS, functions are objects and can be declared anywhere.
  2. If I declare a function within another function, the inner function has access to the local variable of the outer function.
  3. Normally, when a function exists only the return portion is not cleared from memory.
  4. 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?”
  5. 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.

I like the term “backpack” for the closure data and its syntax is [ ]scope[ ] [ ]. The official term from Javascript is the persistent lexical reference, closed over variable environment, or closure. All really confusing terms.

Advanced Javascript and Python programmers use the concept of closure to create data privacy, event handlers, callback functions, partial applications, currying and other functional programming concepts. For data privacy, the inner function declared inside the function belong to that scope – they can only be accessed from methods from within that function. In other words, the outer function does not have access to the inner scope. Closure can also be used to create stateful functions whose return values may be influenced by their internal state.

Closure serves as the gateway between the global execution context and the outer scope. Closure is created at every function call.