-1

I don't understand why the functions are taking the outer scoped variable instead of the nearest one when called as callback.

function outerFn(){
    let x = 1;
    function log(){
      console.log(x);
    };
    function run(fn){
      let x = 100;
      fn();
    }
    run(log);
};
outerFn();

I was expecting the run to log 100 instead of 1.

  • 1
    The set of variables etc. that a function closes over is determined by where the function is **created**, not by where it's **called**. `log` closes over the outer `x`. The fact it's called in a context where there's an inner `x` is irrelevant, it doesn't close over the environment where it's called. (Imagine if it did! **Any** function you called would have access to anything in the scope you called it from!) – T.J. Crowder Jan 21 '23 at 13:02

1 Answers1

0

"x" is being closed over by your "log()" function. Your "log()" function does not have access to "x" declared in "run()".

Benjamin
  • 114
  • 3
  • This is a **very** commonly-repeated duplicate question. Please don't post answers to duplicates. (You can remove the answer by using the "delete" link.) – T.J. Crowder Jan 21 '23 at 13:00