Reputation: 6762
It seems like a stupid question but I really can't wrap my head around it. I began to wonder this when I was thinking of why there is a semicolon after variable declaration but not function declaration. So does that mean a function declaration is an expression?
And what is the official meaning for statement? I've been finding the answer saying that a statement is a "command" that tells computer what to do, but isn't a function declaration telling the computer what to do? Does it have something to do with when it's get loaded when executing the code?
Upvotes: 2
Views: 356
Reputation: 816404
I began to wonder this when I was thinking of why there is a semicolon after variable declaration but not function declaration
Not every statement ends with a semicolon.
Examples of statements with trailing semicolon:
var foo = <expression>;
<expression>;
do <statement> while (<expression>);
Examples without trailing semicolons:
if (<expression>) <statement>
try <block> catch (<identifier>) <block>
for (...) <statement>
{ <statement list> }
So does that mean a function declaration is an expression?
No, it's more complicated than that. Function declarations are not statements. They are not expressions either, they are source elements. Statements and function declarations are both source elements. **
And what is the official meaning for statement?
I can't tell you the official definition, but in the context of JS I would say something like "it's an instruction that does not produce an assignable result/value". Expressions on the other hand produce a result that can be used in other expressions.
** Good to know, but a bit off-topic: Since function declarations are not statements, they are technically not allowed to be used inside blocks. This becomes even more apparent if we also consider hoisting. This example should throw a syntax error in every browser, but unfortunately it doesn't.
if (true) {
function foo() { alert('foo'); }
} else {
function foo() { alert('bar'); }
}
foo();
This leads to different behaviors in different browser. While Chrome will show bar
, Firefox will show foo
. Chrome just hoists both function declarations, and the second overrides the first one. Firefox interprets both declarations as something like a function expression.
Try it yourself in different browsers.
Upvotes: 2
Reputation: 887413
A variable declaration can have side-effects (eg, var x = alert(42);
).
A function declaration cannot.
Upvotes: 2