JavaScript closures: how an inner function keeps its lexical environment
What is a closure?
- A closure is described as the combination of a function and the Lexical environment in which that function was declared,
and it refers to the JavaScript feature that lets an inner function access the variables of the outer (enclosing) function.
Closure example code
js
let func1 = function(){
let a = 1;
let func2 = function (){
return ++a;
};
return func2; //returns the func2 function itself
};
let func3 = func1();
console.log(func3()); // 2
console.log(func3()); // 3👆 Even when the inner function is called outside the outer function, it can access the outer function's local variables.
That is because it remembers the environment it was created in (Lexical environment).
- #Closure
- #JavaScript closure
- #lexical environment