Expressions vs Statements
EasyAll JavaScript code falls into two categories: expressions (produce a value) and statements (perform an action). This distinction explains why some code can go inside other code and some can't, why ternary and if/else work differently, and what console.log actually needs.
Interactive Visualization
Expression
Produces a value
Statement
Performs an action
5 + 3→8
expression"hello"→"hello"
expressionMath.max(1, 5)→5
expressionStep 1/3Expressions PRODUCE values. You can replace them with their result.
💡 Key Insight:Expressions evaluate to values; statements perform actions. This explains where code can go.
Expression: Produces a value
Statement: Performs an action
Key Points
- Expressions produce/evaluate to a value
- Statements perform an action (don't produce a value)
- Expressions can nest inside other expressions
- Statements cannot go where expressions are expected
- The ternary operator is an expression; if/else is a statement
- console.log() needs an expression (something that produces a value)
Code Examples
Expressions Produce Values
// Each of these evaluates to a value: 5 + 3 // → 8 "hello" // → "hello" Math.max(1, 5) // → 5 true && false // → false x > 10 ? "big" : "small" // → depends on x // You can use expressions anywhere a value is needed
An expression can be replaced with its resulting value without changing meaning
Statements Perform Actions
// These DO things but don't produce values: let x = 5; // Declaration statement if (x > 0) { ... } // If statement for (let i = 0; ...) // For statement function foo() {} // Function declaration // You can't assign a statement to a variable: // let result = if (x > 0) { 1 }; // ERROR!
Statements are instructions to do something, not values you can use
Ternary (Expression) vs If/Else (Statement)
// If/else is a STATEMENT - can't use inline let status; if (age >= 18) { status = "adult"; } else { status = "minor"; } // Ternary is an EXPRESSION - produces a value let status = age >= 18 ? "adult" : "minor"; // That's why ternary works in JSX, template literals, etc.
Use ternary when you need a value; if/else when you need branching logic
Why console.log Needs Expressions
console.log(5 + 3); // ✓ Expression → 8 console.log("hello"); // ✓ Expression → "hello" console.log(x > 5); // ✓ Expression → true/false // console.log(let y = 5); // ✗ Statement - ERROR! // console.log(if (x) {}); // ✗ Statement - ERROR! // The argument to console.log must be a value
console.log displays a value - you must give it something that produces one
Common Mistakes
- Trying to use if/else where an expression is needed (use ternary instead)
- Not realizing that assignment (x = 5) is actually an expression too
- Confusing "returns undefined" with "doesn't produce a value"
Interview Tips
- This explains many "unexpected token" errors
- Understanding this helps with React JSX, template literals, and arrow functions
- Expression bodies in arrow functions: () => x + 1 vs () => { return x + 1 }