Search code examples
javascripthoisting

how hoisting works ? difference between function and variable


may i know how this code execute?

function scope() {
  return hosting;

  function hosting() {
    var hosting = '15';
  }
  var hosting = 12;

}

console.log(typeof scope())

here this code return function, we now js engine will move the declaration to top so we get function,

function scope() {
  return hosting;

  var hosting = 12;
}

console.log(typeof scope())

but now why its not return number?, but i know we need to use let to avoid this


Solution

  • It doesn`t return number 12 because hoisting works only for declarating the actual variable, not to assign it a value.

    This means that your code looks like this for compilator:

    function scope() {
        var hosting;
        return hosting;
    
        hosting=12;
    

    }

    Also please remember that everything after return is not executed.