This question has already been answered:

Why does the function declaration go to the beginning of the block, and its identifier is available already at the beginning of the script with an undefined value?

<script> console.log(foo); // undefined if(true) { console.log(foo()); // "hello" function foo() { return 'hello'; } } console.log(foo()); // "hello" </script> 

Reported as a duplicate at Grundy. javascript Feb. 15 at 8:01 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    Starting with es6, functions can be declared inside if blocks. In this case, their visibility area will end with an if area. To avoid such problems with undefined , use the 'use strict' directive, then there will be an error when accessing the undeclared function foo. Without the use of this directive, the result will be the difference depending on the internal implementation of the standard in a particular browser.

     'use strict' console.log(foo); // undefined if(true) { console.log(foo()); // "hello" function foo() { return 'hello'; } } console.log(foo()); // "hello" 

    https://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements