0

var x = 10;
function foo() {
  var y = x + 5;
  return y;
}
function bar() {
  var x = 2;
  return foo();
}


console.log(bar()); // 15

In my view, output should be 7 since foo()'s lexical envt. is bar() and hence value of x should be taken as 2 not 10.

Please correct my understanding

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • Lexical environment is called *static scope* because it doesn't change. It's determined at the time the function is defined. What you describe is *dynamic scope* - calling a function from a different place will change the environment. That's *not* at all what lexical scope is. – VLAZ Mar 30 '22 at 07:38
  • 1
    There's no closure in your example – Bergi Mar 30 '22 at 09:12

0 Answers0