function outer() {
let xx = 0;
function inner(fun) {
console.log(fun());
fun();
return "ds";
}
return inner;
}
const x = outer();
function fun() {
xx++;
return xx;
}
const y = x(fun);
console.log(y);
here the function fun() is called inside a closure function so it should have the data of its static content that is lexical scope and should have values of xx but it is giving reference error please anyone explain me why this is happening.
please anyone explain me why this is happening.
xxis in scope within the context of theouterfunction definition. You're expecting it to exist in a completely separate function, where it absolutely will not be present. Scope absolutely does not extend to functions called within your context. Can you imagine if your functions were subject to the scope of the caller?1If you need access to that, then make your inner function look like:
--
1 No need to have that active an imagination, as this is what happens when you over-use global variables.