Lexical Scoping
Lexical scoping refers to how a parser resolves variable names when functions are nested. The location where a variable is declared within the source code determines where that variable is available. Nested functions have access to variables declared in their outer scope. Consider the following example:
Example 1: This example shows the basic use of closure.
function foo() {
let b = 1;
function inner() {
return b;
}
return inner;
}
let get_func_inner = foo();
console.log(get_func_inner());
console.log(get_func_inner());
console.log(get_func_inner());
Output
1 1 1
Output:
We can access the variable b which is defined in the function foo() through function inner() as the later preserves the scope chain of the enclosing function at the time of execution of the enclosing function i.e. the inner function knows the value of b through its scope chain.
This is closure in action that is inner function can have access to the outer function variables as well as all the global variables.
Note: Closure is the concept of function + lexical environment in which function it was created. so every function declared within another function then it has access to the scope chain of the outer function and the variables created within the scope of the outer function will not get destroyed.
Closure in JavaScript
Closures in JavaScript are functions that retain access to variables from their containing scope even after the parent function has finished executing. They’re useful for maintaining private data, creating modular code, and implementing callback functions with persistent state. In this article, we’ll dive deep into closures, understand how they work, and explore practical examples.
Contact Us