Heuristic definition of an expression
The distinction between expresssions and statements is a tricky one. The standard distinction is that an expression produces a value, while a statement produces a side effect.
I’d like to propose a different, more heuristic definition: an expression is anything that you can stick into a data structure. A statement is anything that you cannot stick into a data structure.
Even more prosaically: an expression is anything you can stick into an array.
This definition is arbitrary and yet quite useful. Judging by it, here’s the things that are expressions:
- Literals (numbers, strings, regexes, arrays, objects).
- Named functions that are already defined.
- Function invocations.
- Increments and decrements.
- Bit operations.
- Logical and mathematical operations.
- String concatenation.
And here’s the things that are statements:
- If/else blocks.
- Variable assignments.
- Named function definitions.
- Try/catch blocks.
- Return statements.
- Errors and exceptions.
I am definitely not ready to explain why expressions are much better than statements as a way of creating elegant, precise, compact code. However, I am quite sure that the more I use expressions, and the less I use statements, the better my code becomes.
It is noteworthy that judging by this heuristic, ternaries and increment/decrement, which are two seemingly un-functional, side effect laden constructs, can work as expressions.