Search code examples
javascriptscopinghoisting

Way to understand this code. How is it working?


I was exploring scopes in javascript and came to know this problem. I don't understand how this problem is working.

function checkType() {
  return foo;
  foo = 10;

  function foo() {};
  var foo = 11;
};

console.log(typeof checkType())

My question is this how does javascript compiler decide to return function not variable. Any reference or explanation are welcome.


Solution

  • This is how the compiler will compile the above code..

    function checkType() {
      var foo = function() {}; /* function will be hoisted to the top, 
                                  and will be assigned to the variable as 
                                  the name is the same for the two.. */
      return foo;
    
      // Code will never reach here as you are returning before this
      foo = 10;
      foo = 11;
    };
    
    console.log(typeof checkType());
    

    Functions which are defined using function() syntax will be hoisted, in this case, the nested function will be hoisted insde the checkType() and hence, the checkType() returns the function instead of the integer.

    Note: Because the function was defined using function(){} syntax, it was hoisted to the parent function scope, else, if the function was defined using var foo = function() {} then the hoisting would not have worked in the same way, your function would've returned undefined instead.

    More reference on Scoping & Hoisting