Statements vs. Expressions
Expressions ask JavaScript for a value. Statements tell JavaScript to do something. Learn the difference.
The Essentials
- Expressions Ask: An expression evaluates to a value. It is like asking JavaScript a question: "What does this evaluate to?"
- Statements Tell: A statement is a command. It tells JavaScript to perform an action, like creating a variable or logging to the console.
- Punctuation: Statements usually end with a semicolon (
;), signaling that the command is complete.
I have talked a lot about expressions: those snippets of code that evaluate to a single value, like "Front" + "end" or 4 + 6. But there is another category of code in JavaScript that you will use constantly: statements.
If an expression is a question ("What is this value?"), a statement is a command ("Do this action.").
What is a Statement?
Take a look at this line of code:
let total = 6 + 4;This entire line is a statement. It is a command that tells JavaScript to do a few things in sequence:
- Create a variable called
total. - Evaluate the expression
6 + 4. - Point the variable
totalto the resulting value.
The 6 + 4 part is an expression because it resolves to the value 10. But the whole line is a statement because it performs an action.
Notice that the statement ends with a semicolon (;). You can think of the semicolon like a period at the end of an English sentence. It tells JavaScript, "I am done giving you this command. Stop and execute it."
Why the Distinction Matters
As you progress in JavaScript, you will learn new syntax that requires you to know whether you need a statement or an expression.
For example, when you want to output a value so you can see it, you use a statement:
console.log(total);console.log() is a statement because it tells JavaScript to perform an action: "Print this to the console."
Later on, when I cover functions, loops, and conditional logic (if/else), you will see many more statements. The key takeaway for now is to recognize that sometimes you are asking JavaScript to conjure up a value (an expression), and other times you are demanding it perform a task (a statement).
Further Reading and Watching
- MDN: Statements and declarations
- FrontendMasters: JavaScript First Steps - The source course for this foundational concept.
Keep reading