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() {}
+function bar() {}; bar();
gives an error saying thatbar
is not defined. Iffunction foo() {}
is being treated as a function expression, then I would think that trying to execute it after would fail, but instead it works. My guess is that it has something to do with the web-compatibility part of the spec. – Horaciohoraefunction
declarations (and yes, that's what that is; it's not afunction
instantiation expression because thefunction
keyword appears at token #1 of a statement context) are scoped to the function in which they appear. Without a "declarative environment record" after theif
, thelet
declaration is near nonsense. If it were allowed, it would be useless except for side-effects of the initialization expression. The lack of any place to "put" the declared symbol is probably more significant. – Dulcyfunction
declaration were considered an error I would not mind at all. – DulcySyntaxError: In strict mode code, functions can only be declared at top level or inside a block
. I would have thought that either top level or inside a block would cover 100% of cases but it looks like I overlooked this possibility. – Noel