I read in this article that function declarations can appear only in statement position. I'm wondering what are these "statement positions".
1 Answer
what are these "statement positions".
Places in the code where it is valid to put a statement.
Syntactic constructs are divided into groups, one of them being statements. The other big group is expressions. In general you can think about the difference between those as that expressions generate values, whereas statements describe what to do purely as "side effects".
For example, the structure of an if statement is
if (<expression>) <statement>
The condition of an if statement needs to be an expression and the body needs to be a statement. A statement can never be put in the place of an expression since it doesn't produce a value.
For example, the addition operator is defined as
<expression> + <expression>
Since an if statement is not an expression, you cannot do
42 + if(...) {}
To learn more about which statements and expressions are available, you can look at the specification, but it's not necessarily an easy read. YDKJS - Grammar might be a bit easier to understand.
I read that function declarations can appear only in statement position.
It's actually a bit more complicated than that. Function declarations are not statements, they are declarations. Officially declarations are only valid at the top level of the global scope and in function declarations. However, most environments allow function declarations in other places, unfortunately evaluating these cases in different ways.
Because of this, ECMAScript 6 added compatibility rules to explain this behavior, but it's not something that should be relied upon. See also Why is a function declaration within a condition block hoisted to function scope in Chrome but not Firefox? .
When the article says "A function declaration is a statement.", then that's certainly a simplification.
if (<expression>) <statement>. The body of a anifstatement needs to be a statement, whereas the condition needs to be an expression. However, that's actually not quite correct. Function declarations are not statements and, officially, are not valid in all statement positions. However, most environments allow it, but apply different evaluation rules. tl;dr: it's complicated.