A function along with its lexical scope bundled together is called a closure
So what do we mean by lexical scope ๐ค lexical scope means the place where the variable or functions is created
Chatting is okay lets chat with code ๐
function x() {
var a=10 // local variable
function y() {
console.log(a)
}
return y;
}
x() // 10In the above code we have a function x within that we have another function y. Function x creates local variable and function y prints it to console.
Function y doesn't have any local variable of its own but it has the access to local variable of its parent function x because of the Closure concept in JavaScript.
function x() {
function y() {
console.log(a)
}
var a=10 // local variable
a++;
return y;
}
x() // 11 Numerous Output questions can be formed on the basis of Closures concept.
To understand Closures properly we need to understand Execution Context first.
Functions run inside a Execution Context
What is execution context ? Its an abstract concept used by ECMAScript to track runtime evaluation of code.
Every function creates an execution context. Execution Context comprises of comprises of variables in the function they were created and reference to the parent's environment. Since execution context got reference to its parent environment. All the variables of parent functions gets available to the inner function. This is a closure.
A closure is created every time an enclosing outer function is called. In other words, the inner function does not need to return for a closure to be created.
That's it for this blog!!
I hope you learnt something from my Blog!
Thank you!! ๐
Built with TypeScript, Tailwind and Next.js โฅ