Search code examples
javascriptscopehoisting

Are ES6 blocks only prevent function hoisting?


Someone please help me understand the following scenario:

//Outer funtion 
function foo() {
  console.log('outer foo');
}

{
  //Inner function
  function foo() {
    console.log('inner foo');
  }
}

foo(); //Says "inner foo"

I assume that in the above case the Inner function's explicit deceleration is replacing the hoisted outer function after the block is executed.

Does this mean that ES6 blocks ONLY prevent function hoisting when declared inside?

Update

It is opined by many that the blocks are not effecting functions. But, please see the following scenario as per MDN -

foo('outside');  // TypeError: foo is not a function
{
  function foo(location) {
   console.log('foo is called ' + location);
  }
  foo('inside'); // works correctly and logs 'foo is called inside'
}

To be more precise, the block statement is preventing the function declaration from being hoisted to the top of the scope. The function is behaving as if it were defined as a function expression and, as such, it is only the implicit variable declaration that gets hoisted to the top of the scope

Another update

The documentation was wrong and it was just fixed by the expert who provided the selected answer.


Solution

  • I assume that in the above case the Inner function's explicit deceleration is replacing the hoisted outer function after the block is executed.

    Function declarations, like var statements, are hoisted to the top of the function during the initial scan of the function before the code within it is executed.

    Blocks aren't relevant to hoisting of var statements or function declarations (both of which has function scope). They only matter for let and const which have block scope.