JavaScript Expressions vs Statements
Expressions
An expression produces a value
1
produces the value1
你好
produces the value你好
5 * 10
produces the value50
age >= 18
produces the valuetrue
orfalse
isHappy ? "🙂" : "🙁"
produces the value🙂
or🙁
(function () { return 'Hi'; }())
produces the valueHi
({a: 1})
produces the value{a: 1}
Statements
Perform actions to complete tasks
Statements are like commands; using them executes some predefined actions. Wherever there are statements, expressions can be input.
// Assign `5` to the `age` variableconst age = 5;
// If `age` is greater than or equal to 18, then execute ...if (age >= 18) { // ...}
Expressions and Statements
An expression produces a value and can stand alone or as part of another statement. Additionally, in special cases, you may need to use ()
to wrap an expression; otherwise, JavaScript may incorrectly interpret it as a statement.
// IIFE Immediately Invoked Function Expression(function () { // ...})();
// Return Objectconst f = () => ({ a: 1 });
Summary
A simple way to distinguish between expressions and statements is to throw them into console.log
. If there are no syntax errors and it can execute, it’s an “expression”; otherwise, it’s a “statement” (or simply invalid syntax). I later realized the importance of expressions and statements, especially with some peculiar restrictions when writing frameworks like React/JSX, such as: “only one element can be returned” and “why use expressions to write?“. In reality, these are limitations of how JavaScript itself operates.