javascriptfunctionecmascript-6

Function declaration is block scoped


It is said that function declarations are block-scoped but the code below cause confusion in my mind. Please if anybody knows some article which reflects the true behaviour of function declaration.

{ // Enter a new scope

  console.log(foo()); // prints hello
  function foo() {
    return 'hello';
  }

}
foo(); // {A} // prints "hello"

If functions would have been block-scoped then why should line {A} have printed "hello" in console.


Solution

  • Problem with the code above is that it ran in sloppy mode, thats why everything went well. But in strict mode line A will return error. Hence, functions are block-scoped.

    'use strict';
    { // Enter a new scope
    
      console.log(foo()); // prints hello
      function foo() {
        return 'hello';
      }
    
    }
    foo(); // {A} // throws error