Statement vs expression in JavaScript
Photo: Statement vs Expression - ReactedNode
What You Should Know
- Understand how to declare and use variables with
let
,const
, orvar
. - Be aware of basic types like numbers, strings, and booleans.
- Know how to perform simple arithmetic and string operations.
What You Will Learn
- What are expressions in JavaScript, and how do expressions evaluate to values and are used
- What are statements in JavaScript, and how do statements perform actions and control the flow of code
- The key difference between expressions and statements in JavaScript
Key Concepts
Expressions
An expression is any valid unit of code that produces a value.
Example:
Expressions in JavaScript have the following characteristics:
- It always returns a value
- It can be used anywhere a value is expected (e.g., as part of an assignment or function argument).
- Can be simple or complex (literals, operators, function calls, etc.).
Simple Expressions
Simple expressions are small, straightforward pieces of code that evaluate to a single value. These don't involve any operations—just literal values or identifiers.
Complex Expressions
Complex Expressions combine multiple values, operators, or function calls but still result in a single value.
Even though they're made up of smaller parts (which might be simple expressions themselves), they still evaluate to one final result.
Statements
A statement is a unit of code that performs an action.
Statements in JavaScript have the following characteristics:
- Does not always return a value
- Often controls the flow of the program
- Can contain expressions inside them
Statements vs Expressions
Type | Returns a Value? | Can Be Used as a Value? | Purpose |
---|---|---|---|
Expression | Yes | Yes | Compute or evaluate something |
Statement | Not always | Not directly | Perform an action or control flow |
Why it matters
Misunderstanding expressions vs. statements can lead to subtle issues with features like arrow functions.
It returned undefined
because the curly braces turn it into a statement block, and without a return, nothing gets returned.
In the above example, undefined
was returned by the function getUserName
because the function's curly braces turn it into a statement block, and nothing gets returned without a return
.
To correctly handle it, we can either add a return statement or rewrite them like this:
Apart from this, some JavaScript features like ternary operators and logical short-circuiting only work with expression. Knowing what qualifies as an expression lets you write cleaner logic.