What closure actully do?
Suppose you have a simple pice of code like this.
let value = 1
function multiply(){
value = value * 2;
console.log(value)
}
multiply() // output: 2
multiply() // output: 4
multiply() // output: 8
console.log(value) // 8
if you see here we have a variable in global scope and a function what multiply value*2 and assign it to value variable and console it.
Now take another code
function multiply(){
let value = 1
value = value * 2;
console.log(value)
}
multiply() // output : 2
multiply() // output : 2
console.log(value) // output: ReferenceError: value is not defined
if you see here we have a variable in functional scope and a function what multiply
value*2
and assign it to value variable and console it.
let's discuss what is the difference in this two codes ?
Now discuss about variable life time
In first code variable has life time util close the window or nevigate another page as it is in global scope
In second code variable has life time util function execution. After complete the execution of this it will be destroy all variable. for this reason when I console value in 2nd code get
ReferenceError: value is not defined
I think you identify the problem already if you are clever.
In First code when I am trying to get updated value and it happend because it update in global scope variable and we know global scope exist util nevigate or close window that's why we are getting expected result.
But when I created a function after execution it will delete all variable and execution steps that's why when I try to get value it will always getting 2. Now what is the solutions the solutions is I need something what will do this in innerscope and throw it after execute in global scope so that we can get updated value.
let's do this.
function multiply() {
let value = 1;
function mul() {
value = value * 2;
}
mul();
return value;
}
const mul1 = multiply()
const mul2 = multiply()
console.log(mul1, mul2) //output 2 2
Still problem not solved expected 4 but getting 2 let's solve this by return insted of value variable let's return the the inner/nested function
function multiply () {
let value = 1;
function mul() {
value = value * 2;
return value
}
return mul
};
const mul = multiply()
console.log(mul()) // 2
console.log(mul()) // 4
console.log(mul()) // 8
So finally define what is Closures?
A closure is a feature of JavaScript that allows inner functions to access the outer scope of a function. Closure helps in binding a function to its outer boundary and is created automatically whenever a function is created.
Top comments (0)