In JavaScript, a closure is a function that has access to the variables in its outer (enclosing) function's scope chain. The closure has access to variables in three scopes:
1. Variables in its own scope (variables defined between its curly brackets)
2. Variables in the outer function's scope
3. Variables in the global scope
Here's an example of a closure in JavaScript:
function outer() {
let outerVar = 'I am an outer variable';
function inner() {
console.log(outerVar);
}
return inner;
}
let closure = outer();
closure(); // prints "I am an outer variable"
In the example above, the inner() function is a closure because it has access to the outerVar variable from the outer() function's scope.
When the closure variable is called, it logs the value of outerVar to the console, even though outerVar was defined in the outer function and closure is called outside of that function.
This is possible because when the inner() function is returned from the outer() function, it retains a reference to the outerVar variable. This is known as a closure because it "closes over" the variables in the outer function's scope, making them available to the inner function even after the outer function has finished executing.
Comments (0)