Search code examples
javascriptscopelet

Javascript let hoisting to the scope or creating where it is?


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


Solution

  • 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