StatementA single piece of code that accomplishes one task or action
ExpressionA statement that produces a value
OperatorSymbols that are used to assign, compare, and perform operations
"hello"; 358; false; console.log('BOOM'); alert('POW');
An expression is a statement that, when read by the browser, results in a single value. Expressions can use operators to create this single value. Here are some example expressions:
This expression results in “apple”:
"ap" + "ple"
This expression results in 5:
2 + 3
What is the difference?
In simpler terms, a statement performs some kind of action. It does not return anything. An expression produces a value and can be written wherever a value is expected.
Think about the following sentences:
- “It’s raining a lot!”
- “It’s raining cats and dogs!”
Both of these sentences are statements! They declare something. But one of them is an expression - it means something other than what the letters actually spell out. “It’s raining cats and dogs” ACTUALLY means “It’s raining a lot”.
Similarly, consider the following code statements:
2 + 2;
They’re both statements. One is an expression -
2 + 2; evaluates to
Expressions rely on operators to calculate their single value. There are 5 basic types of operators to get you started:
- Assignment operators assign a value to a variable.
var color = 'magenta';
- Arithmetic operators perform basic math.
var addTwo = 2 + 2;
- String operators combine strings.
var greeting = 'Hello! ' + 'Nice to meet you.';
- Comparison operators compare two values and return a true or false.
var buy = 3 > 5; // Value of buy is false
- Logical operators combines expressions and return a Boolean value of true or false.
var buy = (5 > 3) && (2 < 4);
Example: Check if 2 is greater than or equal to 3
2 >= 3
- Find 12 divided by 3
- Find the remainder when 12 is divided by 5
- Combine the strings “hello” and “world” and “!”
- Check if “4” is the exact same thing as 4
- Write a variable age and assign to a number. Check if the age is greater than 21 but less than 65.