Encapsulation
Hide implementation details and temporary state inside a function.
JS Puzzles · Const
Function scope limits a function's local declarations to that function. Nested functions can access enclosing scopes, creating a scope chain where nearer bindings shadow outer ones.
A function creates its own scope. Names declared inside it are unavailable to outside code, while the function can read names from surrounding scopes. Nested functions can retain access to enclosing bindings, forming a scope chain.
function functionName(parameters) { statements }function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2
The returned function keeps access to the outer function's local binding.
Hide implementation details and temporary state inside a function.
Build callbacks that retain access to variables from their creation context.
Resolve names across nested functions using lexical scope.
scope chainclosuresnested functionsfunction declarationsfunction expressions