In JavaScript, a closure is created when a function is defined inside another function, and the inner function retains access to the variables of the outer function, even after the outer function has finished executing.
How it works:
Lexical Scoping:
JavaScript uses lexical scoping, which means a function's scope is determined by where it is defined in the code.
Inner Function Access:
An inner function has access to its own scope, the scope of its parent function, and the global scope.
Closure Creation:
When the outer function is called, it creates an environment that includes its variables. The inner function, when returned, retains access to this environment even after the outer function completes
function outerFunction(x) {
var innerVariable = 10;
function innerFunction() {
return x + innerVariable;
}
return innerFunction;
}
var closure = outerFunction(5);
console.log(closure()); // Output: 15
Top comments (0)