Closure in JavaScript
In JavaScript, a closure is a combination of a function and the lexical environment within which that function was declared.
This environment consists of variables and values available at the time the closure was created. Closures allow a function to access and remember the scope in which it was created, even after that scope has finished executing.
Here's a simple example to illustrate closures:
function outerFunction() {
// Outer function has a variable 'outerVar'
let outerVar = 'I am from outerFunction';
function innerFunction() {
// Inner function can access 'outerVar'
console.log(outerVar);
}
return innerFunction; // Return the inner function, creating a closure
}
const closureExample = outerFunction();
// Invoke the closure, which remembers the 'outerVar' from its lexical scope
closureExample(); // Output: 'I am from outerFunction'
In this example, innerFunction is defined inside outerFunction, and it has access to the outerVar variable. When outerFunction is invoked, it returns innerFunction, creating a closure. The closure retains access to the outerVar variable even though outerFunction has finished executing.
Closures are powerful because they provide a way to create private variables, maintain state, and encapsulate functionality. They are commonly used in scenarios like creating factory functions, managing private data, and implementing callback functions.