In the MDN documentation for "Statements and declarations" it is mentioned:
The terms "statement" and "declaration" have a precise meaning in the formal syntax of JavaScript that affects where they may be placed in code. For example, in most control-flow structures, the body only accepts statements — such as the two arms of an if…else. If you use a declaration instead of a statement, it would be a SyntaxError. For example, a let declaration is not a statement, so you can’t use it in its bare form as the body of an if statement.
The following code will give an error:
if(true)
let x = 0;
Now functions declarations are also just declarations right? Then why doesn’t the following code give the same error?
if(true)
function foo() {}
3
Answers
In this case, the foo function will only be defined within the block of the if statement, adhering to block scope rules.
Because declaring a function using the function keyword puts it in the global scope.
Make a simple test:
Will result in ‘7’ in the console, proving that the function was actually defined outside the if.
On the opposite the variable explicitly defined inside the if will be scoped to the if.
Note this code will raise an error because bar will not be defined outside the if.
Edition 5.1 has a note specifically addressing this problem:
From the next edition through the current one, the first construct is covered by an additional feature specified in Annex B, which is required when the host is a web browser:
IfStatement[Yield, Await, Return]: