简体   繁体   中英

Why is a function declaration not a statement while a variable declaration is

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?

A variable declaration can have side-effects (eg, var x = alert(42); ).

A function declaration cannot.

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:

  • Variable declaration: var foo = <expression>;
  • Expression statement: <expression>;
  • Do while loop: do <statement> while (<expression>);

Examples without trailing semicolons:

  • If statement: if (<expression>) <statement>
  • Try catch statement: try <block> catch (<identifier>) <block>
  • For loop: for (...) <statement>
  • Block 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM