a
is in block scope for the anonymous function
returned by calling add
and
b
is in the closure scope for the anonymous function
returned by calling add
so a function is going to keep any variables needed in the closure scope even when the outer function has exited and all its local variables are garbage collected except b which is needed for the anonymous function . hence it lives in the closure scope of it
hence you may add more to closure scope like so;
if (true) {
let a = 40;
function add(b) {
let d = 55;
return () => {
let c = a + b +d;
console.log(c);
}
}
console.dir(add(10));
}
now in the closure scope we have b
and d
( they both are local variables to function add and are needed by the inner function)
similarly if the variable d
was not required, then it won't be in its closure scope like so
if (true) {
let a = 40;
function add(b) {
let d = 55;
return () => {
let c = a + b;
console.log(c);
}
}
console.dir(add(10));
}
now in the closure scope we only have b
.
so its not the function passed in parameter that is assigned in closure scope. it can be any local variable which is needed. for eg:
if (true) {
let a = 40;
function add(b) {
let d = 55;
return () => {
let c = a + d;
console.log(c);
}
}
console.dir(add(10));
}
now we dont have b
in closure even it is a passed parameter. its just d
in closure scope.