sures , sure some beginner might faced this too.
What is a Closure?
taken from medium article
So with my understanding with some energy being spent on it, I made example
Please correct me if I am wrong
In this scenario, my grandpa brought 1000 BTC 🤑 and saved to Bitcoin bank,later he spent some BTC (200) and the rest is given to my Dad ,later my dad brought house (300 BTC) and given the rest to me.I donated (499 BTC) to
In above example consider method 2, at first we are invoking the
sum function and setting the
a value (by passing as param)in that function scope.
var call_1 = sum(1);
the return function stored in var
call_1, if we log call_1 we will see this
return a + b; // takes "a" from the outer lexical environment
Now just look the variable
call_1 as a typical function, now we can invoke it by calling call_1(4) which will gives the sum of two numbers, but wait we learnt that function scope variable die when scope/function ends, right. then how come the
call_1 manages to get the variable defined in immediate parent even after that parent function already returned,so it should have dead.
Execution context, please refer this site.
as per it EC ,
Scope chain hold the variable object of its own, outer function's variable object , and global execution context variable.
Now this is the reason why you gets
var a available , when invoking
call_1().make sure it gets the reference not the actual value of outer function variable.
When we call function
BTCbank(BTC_balance), we are just initializing
BTC_balance var to
1000 and returning the function
grandpa to var
check that closure have variable
BTC_balance initialized to
Now we can invoke
bankBalance by calling
BTCbank will gets the
BTC_balanace from previous initialization in immediate outer scope of current function (in previous call we already initialized it to 1000 ) and subtracts the passed value.So we do not have to track balance sheet,
BTCbank will do it for you.The returned function placed in
afterGrandpaSpending(200) , will triggers
dad function because that is what variable
BTC_balance from it's immediate outer function , which has
700. The passed value will be subtracted from
BTC_balance.The returned function will be stored in variable
afterdadSpending(499) doesn't return a function instead a value unlike above invoked functions.The returned value stored to