0

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.

  • 3
    Lexical scope is defined by where the function is defined, not where it's called. Since `fun()` is defined in the global scope, it can't access local variables inside other functions. – Barmar Apr 19 '23 at 20:33

1 Answers1

0

xx is in scope within the context of the outer function 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?1

If you need access to that, then make your inner function look like:

function inner(fun) {
  // ...
  xx = fun(xx)
  // ...
}

--

1 No need to have that active an imagination, as this is what happens when you over-use global variables.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    "*Can you imagine if your functions were subject to the scope of the caller?*" - yes. It's called [dynamic scope](https://en.wikipedia.org/wiki/Scope_(computer_science)#Dynamic_scope) – Bergi Apr 20 '23 at 00:08