-2

x declared after fn function but returns its value. Why fn didn't return undefined?

function doWork(){

  let fn = function(){ return x; }
  let x = 2;

  return fn();

}

console.log(doWork()); // 2
Intervalia
  • 10,248
  • 2
  • 30
  • 60
uzay95
  • 16,052
  • 31
  • 116
  • 182

1 Answers1

1

Inside of your doWork() function, first you set up a function and assign it to fn -- This function is not invoked yet. You then define x as 2. After this definition you invoke fn() by calling return fn().

Because JavaScript works from top-to-bottom, x is defined at the time you reference fn(), so fn() is able to return x correctly.

This can be seen in the following:

function doWork() {
  let fn = function() {
    return x;
  }
  let x = 2;
  return fn();
}

console.log(doWork()); // 2
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71