JavaScript Expressions vs Statements

Expressions

An expression produces a value
  • 1 produces the value 1
  • 你好 produces the value 你好
  • 5 * 10 produces the value 50
  • age >= 18 produces the value true or false
  • isHappy ? "🙂" : "🙁" produces the value 🙂 or 🙁
  • (function () { return 'Hi'; }()) produces the value Hi
  • ({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` variable
const 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 Object
const 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.

References