Statements vs Expressions
A statement performs some action
An expression evaluates to some value
print("Hello World") sleep(1000) return 55 if (done) exit() throw SomeError()
"Hello World" 1000 5 + 3 a * 5 > b x_flag & mask
An expression can be part of a statement:
while (x < 5) x += 15 print("i: " + i)
A statement is never part of an expression.
…statements typically don't have a type. If they do, the type is typically something like
…all expressions have types.
"Hello World" is a string,
5 + 7 is an integer and so on.
Some expressions such as
i++ (unary increment in C-like languages) have side-effects and could be viewed as statements embedded in expressions:
while (i++ < 15) …
Some things can be used both as expressions and statements. A call to a function returning a value for example. In C-like languages they need to be terminated by a
; to form a complete statement.
myFunction(); // As statement if (myFunction()) // As expression print("Returned true!");
In scripting languages it's also common to use short circuiting boolean expressions. In shell scripting you often see things like
compile_code || exit 1
or in PHP where the following is a common pattern
fopen($site, "r") or die("Unable to connect");