What are scope and closures?
Scope determines where a name is visible. A closure is what happens when a function keeps access to its scope after that scope would otherwise be gone. The second is the one that confuses people, and it follows directly from the first.
Scope, briefly:
Global scope — visible everywhere.
Function scope — visible within the function.
Block scope — visible within braces, which is what let and const introduced to JavaScript, where var had only function scope.
Lexical scoping — the rule almost all modern languages use. What a name refers to is determined by where the code is written, not by where it is called from. You can determine scope by reading the source, which is why it is also called static scoping.
The scope chain. When a name is used, the innermost scope is checked, then the enclosing one, outward to global. The first match wins — inner names shadow outer ones.
Closures. A function defined inside another function can use the outer function's variables. Normally the outer function's local variables would be discarded when it returns. But if the inner function survives — returned, stored, passed as a callback — it keeps those variables alive. The function plus its retained environment is the closure.
What closures are actually used for:
Private state. Variables in the enclosing scope are reachable only through the returned function, giving genuine encapsulation without any class machinery — a counter that cannot be tampered with.
Callbacks and event handlers that need context from where they were created.
Partial application — a function that returns another function with some arguments already fixed.
Module patterns, historically the main way JavaScript achieved privacy.
The classic gotcha: creating functions in a loop with var gives every closure the same variable, so all of them see the final value. With let, each iteration gets its own binding and they behave as expected. This single example explains most closure confusion.
Closures retain memory, so a long-lived closure holding a large object prevents its collection.