Closure:
- A function, along with its lexical scope, is bundled together to form a closure.
- Accessing the variables of a function even if its execution is completed or out of its scope.
- Closure is a logical way to access the local variables in a global scope.
- A function bundled with its lexical environment is known as a closure. the function is returned, even if it vanished in the execution context, but still, it remembers the reference it was pointing to. It's not just that function alone it returns, but the entire closure, and that's where it.
- In JavaScript, when we return a function from another function, we are effectively returning a combination of the function definition along with the function's scope. This would let the function definition have an associated persistent memory that could hold onto live data between executions. That combination of the function and its scope chain is what is called a closure in JavaScript.
- Closure remembers the outer function scope even after creation.
function outer(){
var a=1000;
function inner(){
console.log(a)
}
return inner //or put the return keyword before the function declaration
}
var v=outer();
Explanation:
- Returned the Function and its lexical scope and put it inside the v1 variable
- When you execute V1 somewhere else in your program, and it still remembers the outer function
Key points :
Function, along with its lexical scope, bonds together to form a closure
Example :
function x(){
var v =10;
function x(){
console.log(v)
}
return x;
}
var res = x();
console.log(res) // it will print the x() function code
res() // it will print the 10
**(Or)**
return function x(){
console.log(v)
}
Example_2 :
function x(){
var v =10;
function x(){
console.log(v) //500
return v
}
v = 500;
return x;
}
var res = x();
console.log(res()) //500