Expression vs. Statement
After completing this topic:
You will be able to clearly distinguish between expressions and statements, and you will be able to solve the question "Why can't I use an if statement here?" on your own.
Two Basic Units of Programming
When writing code, there is a fundamental distinction:
- Expression: A piece of code that produces a value.
- Statement: A unit of code that performs an action.
Understanding this distinction will help you answer the question: "Why does this code cause an error when I put it here?"
Expression: Producing a Value
An expression is code that, when evaluated, results in a single value:
// These are all expressions
5 // Number literal β 5
"hello" // String literal β "hello"
2 + 3 // Arithmetic β 5
x > 10 // Comparison β true or false
isValid ? "OK" : "X" // Ternary β "OK" or "X"
myFunc(42) // Function call β return valueThe key characteristic of an expression: It can be assigned to a variable.
const result = 2 + 3; // β
const msg = isValid ? "OK" : "X"; // β
const val = myFunc(42); // β
If it can be placed on the right side of =, it's an expression.
Statement: Performing an Action
A statement is a command that causes the program to do something:
// These are all statements
let x = 5; // Variable declaration
if (x > 3) { console.log("hi"); } // Conditional statement
for (let i = 0; i < 5; i++) {} // Loop statement
function greet() {} // Function declaration
return x; // Return statementStatements do not produce a value. Therefore, they cannot be assigned to a variable:
const result = if (x > 3) { "yes" }; // β SyntaxError!
const loop = for (let i = 0;;) {}; // β SyntaxError!Why is the Distinction Important?
JavaScript has places where only expressions are allowed. A common example is the curly braces in JSX:
// React JSX
<p>{isAdmin ? "Admin" : "Regular User"}</p> // β
Ternary is an expression
<p>{if (isAdmin) { "Admin" }}</p> // β `if` is a statementOnly expressions can be placed inside the {} in JSX. Since if is a statement, it cannot be used. Instead, use the ternary operator (? :).
// Similarly, in template literals
const msg = `Status: ${count > 0 ? "Present" : "Absent"}`; // β
const msg = `Status: ${if (count > 0) "Present"}`; // βThings That Cross the Boundary
Some code can be both an expression and a statement:
// Function call β it's an expression, but can be used as a statement
console.log("hello"); // Expression statement
// Assignment β it's an expression, but can be used as a statement
x = 5; // Assignment expression (value = 5)
// Function declaration vs. function expression
function add(a, b) { return a + b; } // Function declaration (statement)
const add = function(a, b) { return a + b; }; // Function expression (expression)
const add = (a, b) => a + b; // Arrow function (expression)If it starts with the function keyword, it's a statement (declaration); if it's assigned to a variable, it's an expression (expression).
Common Patterns in Practice
Situations where you need to use an expression instead of a statement often arise:
// Use ternary instead of if/else
const status = score >= 60 ? "Passed" : "Failed";
// Use logical OR instead of if/else
const name = user.name || "Anonymous";
const display = isVisible && <Component />;
// Use object mapping instead of switch
const messages = {
success: "Successful",
error: "An error occurred",
loading: "Loading..."
};
const msg = messages[status] || "Unknown status";Immediately Invoked Function Expression (IIFE)
This is a pattern where a function is defined and executed immediately. Wrapping a function declaration in parentheses turns it into an expression:
// Function declaration β statement
function greet() { return "Hello"; }
// Immediately Invoked Function Expression (IIFE) β expression
const result = (function() {
return "Hello";
})();
console.log(result); // "Hello"IIFE is used to isolate variable scope. While the use of ES6 block scope (let, const) has reduced its frequency, it can still be found in library code or module patterns.
Arrow Functions and Expressions
Arrow functions automatically return the expression if written without curly braces:
// Curly braces + return β the body is a statement
const double = (x) => { return x * 2; };
// No curly braces β the body is an expression (automatic return)
const double2 = (x) => x * 2;
// Parentheses are needed when returning an object literal
const makeUser = (name) => ({ name, role: "user" });This difference is practically revealed in array method chaining:
const prices = [100, 250, 50, 300];
// Expression body β concise
const discounted = prices
.filter(p => p > 100)
.map(p => p * 0.9);One-Line Rule
| Question | Expression | Statement |
|---|---|---|
Can it be put in const x = ___? | β | β |
| Does it produce a value? | β | β |
| Can it be part of another piece of code without a semicolon? | β | β |
"Does this code produce a value?" β This single question is all you need to differentiate. If it produces a value, it's an expression; if it only performs an action, it's a statement.
Differences in Other Languages
The boundary between expressions and statements varies from language to language:
# Python: if is a statement, ternary is an expressionstatus = "Passed" if score >= 60 else "Failed" # expression# if score >= 60: print("Passed") # statement
# Python: assignment is a statement (3.8+ walrus operator is an exception)if (n := len(data)) > 10: # := is an expression for assignment print(f"{n} items")// Rust: if is an expression (returns a value)
let status = if score >= 60 { "Passed" } else { "Failed" };While JavaScript has if as a statement and ternary as an expression, Rust has if itself as an expression. When learning a new language, understanding this boundary first will help you quickly grasp the syntax.
Template Literals and Expressions
Template literals, which use backticks (`), also allow only expressions inside ${}:
const name = "Cheol-soo";
const age = 25;
// β
expression
const greeting = `Hello, ${name}! You are ${age >= 20 ? "an adult" : "a minor"}.`;
// β statements cannot be placed inside
// `${if (age >= 20) { "adult" }}` β SyntaxErrorExpression Statement: Something That's Both
There is also code that is both an expression and a statement:
// Function call β it's an expression, but can be used as a statement
console.log("hello"); // statement used on its own
const x = console.log; // expression that returns a value (function)
// Assignment is also an expression and a statement
let a;
a = 5; // statement used on its own
const b = (a = 10); // expression that returns the assigned value (10)This distinction is the same in JavaScript and most other programming languages. When you encounter "places where values are needed," such as React, template literals, and array methods, this concept will come up.