Closures in JavaScript
Closure is a function along with its lexical environment forms a closure that is called closure.
What is lexical Environment?
In Simple language lexical scope is a variable defined outside your scope or upper scope is automatically available inside your scope which means you don't need to pass it here.
What happen line 4. so inside c() it forms a closure with the a() lexical scope. c() function is bind to the variable of b that means if forms a closure and it has access to parent lexical scope.let str = "javaScript";myFun = () => {console.log(str);}myFun();
consider this example x() it return function y so what will print in console, yeah it print function y likefunction x() {var a = 10;function y() {console.log(a);}return y;}var z = x();console.log(z);z();
function y(){ console.log(a); }and what will be return after calling z()?
it return 7 but why?
because this is not return only y function, it return whole closure. the closure enclosed function along with its lexical environment that was return and it was put inside z so that's why it return 7.
function along with its lexical bundle together form a closure.
Post a Comment