Closures
A closure is a function that remembers and can access its lexical scope, even when the function is executed outside that scope.
Example
function outerFunction() { let outerVariable = "I'm outside!";
function innerFunction() { console.log(outerVariable); }
return innerFunction;}
const closure = outerFunction();closure(); // Output: I'm outside!
Explanation: Here, innerFunction
is a closure because it remembers the outerVariable
from its lexical scope, even after outerFunction
has finished executing.
Application: Closures are commonly used for data encapsulation and to create function factories.