Statements vs Expressions in JavaScript

The terms “statement” and “expression” are thrown around quite a bit in the JavaScript world. But what do they mean?

Statement

For example, if, while, and for are statements; they perform actions or control actions but don’t resolve to values.

x = 5; is a statement because its effect is assignment (it is changing x).

Although semicolons are automatically inserted where needed thanks to automatic semicolon insertion (ASI), it’s still considered good practice to insert a semicolon at the end of a statement (except for function, if, switch, try, and while statements, where they are not needed). The documentation for Douglas Crockford’s code quality tool JSLint states:

JavaScript attempts to make those semicolons optional with an automatic semicolon insertion mechanism, but it does not work very well. Automatic semicolon insertion was added to make things easier for beginners. Unfortunately, it sometimes fails. Do not rely on it unless you are a beginner.

Expression

You cannot provide a statement where an expression is expected — for instance, passing an if statement as an argument of a function.

Some examples:
newDate(); (produces an object)
[1, 2, 3] (produces an array object)
5 + 6 (evaluates to the value of 11)

And there you have it! Statements (which are often not expressions) do something, while expressions are statements whose action is resolving to a value.

aspiring web developer | nataliecardot.com

aspiring web developer | nataliecardot.com