CLOSURES
A closure is created when a function is defined within another function, allowing the inner function to access variables from the outer (enclosing) function's scope even after the outer function has finished executing. This behavior is possible because the inner function "closes over" the variables it references, capturing them in a scope chain.
Here's a simple example to illustrate closures:
1function outerFunction() {
2 let outerVariable = 'I am from the outer function';
3
4 function innerFunction() {
5 console.log(outerVariable);
6 }
7
8 return innerFunction;
9}
10
11// Create a closure by calling outerFunction and assigning the returned inner function to a variable
12const closureExample = outerFunction();
13
14// Execute the closure, which still has access to the outerVariable
15closureExample(); // Output: I am from the outer function
16
In this example, innerFunction is defined inside outerFunction, and it has access to outerVariable. When outerFunction is called and its return value is assigned to closureExample, it creates a closure. Even though outerFunction has completed execution, closureExample can still access and use outerVariable.
Closures are useful for creating private variables and maintaining state within functions. They are commonly used in scenarios like creating function factories, implementing data encapsulation, and handling asynchronous code.