- Instructions (statements) are executed
- Expressions (values) are evaluated
Here is one of my favorite ways to illustrate it:
In JavaScript if we nest console.log
console.log(console.log(console.log("AnAmazingValue")))
we get
AnAmazingValue
undefined
undefined
And in Scala
println(println(println("AnAmazingValue")))
returns
AnAmazingValue
()
()
To conclude, JavaScript instruction console.log
does not return a value (hence the undefined
), while Scalas println
expression returns the value ()
of type Unit
.
Top comments (2)
This basic classification works for simple programs, but I think it misses the real divide by a bit. It would be difficult to classify a snippet like
Looking back at the clearer cases, there are also some problems:
Because you can write
console.log(console.log(5))
at all, we must know thatconsole.log(5)
is in fact an expression, since function arguments are expressions (it simply evaluates toundefined
). In fact, when you writesomething;
what you're writing is called an "expression statement" which tells you to "execute" that expression.You can observe that it is in fact "executing" the expression because expressions that you would otherwise want to call merely 'evaluated' take time to execute, they can throw errors, or they can hang and never let anything else execute.
You can make a much more fine-grained classification of expressions by identifying their side effects. A side effect is something that evaluation of an expression results in other than the value computed.
console.log
has a side effect of printing something to the console.accumulate
from above has a side effect of increasing thetotal
variable.+
on its own is side-effect-free, sometimes called a "pure" expression.This analysis is even more important in the context of languages with more expressive classification of values like Haskell, in which case you can precisely annotate most of the side-effects that each expression has. (Though, not whether or not they hang or throw errors)
undefined
(in JS) ~void
(in Java) ~Unit
(Scala)Maybe you meant expressions vs statements
Statement:
Expression: