I highly recommend reading Dr. Axel Rauschmayer's comprehensive blog post
Expressions versus statements in JavaScript
as mentioned in @ZER0's accepted answer above.
But my favorite memory shortcut is:
Expression:
e
can be set E
qual to an Expression
..orExpressed
by printing it.
Statement:
..anything else.
The following is modified from
Anders Kaseorg's Quora answer.
A statement is a complete line of code that performs some action.
E
very E
xpression can be used as a statement
(whose effect is to evaluate the expression, and ignore the resulting value).
But an E
xpression is any section of the code that e
valuates to a value
.
Expressions can be combined “horizontally” into larger expressions using operators.
E
has a horizontally flat top
Most statements cannot be used as expressions.
Statements can only be combined “vertically” by writing one after another, or with block constructs.
S
runs vertically in comparison.
From Quora Post by Ryan Lam:
Here’s a general rule of thumb: If you can print it, or assign it to a variable, it’s an expression. If you can’t, it’s a statement.
Here are some examples of expressions:
2 + 2
3 * 7
1 + 2 + 3 * (8 ** 9) - sqrt(4.0)
min(2, 22)
max(3, 94)
round(81.5)
"foo"
"bar"
"foo" + "bar"
None
True
False
2
3
4.0
All of the above can be printed or assigned to a variable.
Here are some examples of statements:
if CONDITION:
elif CONDITION:
else:
for VARIABLE in SEQUENCE:
while CONDITION:
try:
except EXCEPTION as e:
class MYCLASS:
def MYFUNCTION():
return SOMETHING
raise SOMETHING
with SOMETHING:
None of the above constructs can be assigned to a variable. They are syntactic elements that serve a purpose, but do not themselves have any intrinsic “value”. In other words, these constructs don’t “evaluate” to anything. Trying to do any of the following, for example, would be absurd, and simply wouldn’t work:
x = if CONDITION:
y = while CONDITION:
z = return 42
foo = for i in range(10):
eval
uate JS code makes me think that all statements are expressions in JS – Sebastiansebastianodo
–while
loop repeat the last value after the end?. – Fash