-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
  • 9,298
  • 1
  • 27
  • 53
uzay95
  • 15,294
  • 28
  • 111
  • 175

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
  • 39,491
  • 10
  • 44
  • 66