Closures🔥
- A function, bundled together with its lexical scope, forms a closure.
- A closure provides access to an outer function's scope from an inner function.
function x() {
var a = 7;
function y() {
console.log(a) ;
}
y() ;
}
x() ;
// 7
In this program, when y() tries to run, it looks for 'a' in its local memory. Since it does not find it there, it accesses its lexical parent, x.
function x() {
var a = 7;
function y() {
console.log(a) ;
}
return y;
}
var z = x() ;
console.log(z) ; //Æ’ y() {console.log(a); }
z() ; // 7
In the above program, the console.log statement returns the function y() (i.e., function y() { console.log(a); }). When 'y' is returned, the function is returned, and the entire closure (the function y along with its lexical scope) is returned and assigned to 'z'. As a result, when 'z' is used elsewhere in the program, it still retains access to the variable 'a' inside x(). Even though x() no longer exists, the 'y' function remembers its lexical scope, allowing z() to output 7.
Whenever a function is returned, even if it vanishes from the execution context, it still retains the reference it was pointing to. It does not return just the function alone but the entire closure.
function z() {
var b = 100;
function x() {
var a=7;
function y(){
console.log(a,b);
}
y();
}
x();
}
z();
In the above image, 'y' forms a closure with the scope of 'x' and the scope of 'z'.
Credits to Akshay Saini. [(https://youtu.be/qikxEIxsXco?si=sRe_4k5swSbnr50T)]
Top comments (0)