JavaScript Closures
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
Lexical Scoping
To understand closures, you must first understand Lexical Scope. "Lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope. This happens automatically when parsing the code.
The Magic Backpack
Normally, local variables within a function only exist for the duration of that function's execution. Once the function finishes, they are destroyed. However, if that function returns an inner function, JavaScript preserves the outer function's environment because the inner function might need it later. It creates a "backpack" attached to the returned function containing all the variables it needs to survive.
Practical Use: Data Privacy
Closures are crucial for creating private variables. Since JavaScript didn't historically have a native way to create private properties in objects (like `private` in Java), developers used closures. By defining variables inside a function and returning an object with methods to access those variables, you restrict direct access from the outside world. This pattern is known as the Module Pattern.
Closures in Loops (Classic Interview Question)+
A very common problem occurs when combining loops, `setTimeout`, and the `var` keyword.
Because `var` is function-scoped, all timeouts share the same `i`. By the time the timeout runs, the loop has finished and `i` is 3. The modern solution is simply to use `let`, which provides block scope, creating a new closure environment for every iteration!
