So, my understanding is that the distinction between a statement and an expression is that a statement is a line of code that performs some action, whereas an expression produces a value. Further, while it makes sense that not all statements are expressions because not all resolve to a value (as in the cases of if, while, and for), if an expression produces a value, isn't that considered doing something, and therefore also a statement?
Since you asked the question tagged with computer-science as well as javascript I thought I'd point out that JavaScript is different to several other popular languages in this regard.
For example, in Java and C# you cannot use an arithmetic expression as a statement.
public class C {
public void M() {
1 + 2;
}
}
The C# compiler rejects this code with message:
error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
A similar error is produced by the Java compiler:
error: not a statement
Such an expression has no observable effect in code, therefore computing it is pointless. The compiler designers chose to flag this as a compile error, presumably to help developers avoid a class of mistakes in their code.
Kotlin produces a warning:
Warning: The expression is unused
The D compiler (dmd) produces:
Error: + has no effect in expression (1 + 2)
GCC 6.3 (both for C and C++) doesn't seem to complain (though it might do if you turn on -Wall or other extended warnings).
Swift also doesn't complain.
So although JavaScript permits such expressions as statements, I would argue that it's a weakness of the language specification rather than a strength. If the return value is not applied anywhere then it's a waste of computation (either at runtime, or at JIT time) and potentially hides a bug, such as a missing return statement.
One final note is that some compilers may be able to elide the expression if it can determine it has no side effects. As an example 1 + 2 + doSomething() cannot be completely removed if doSomething does anything observable (such as print to the screen or update shared state), however the preceding addition operations could be discarded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With