Operators and Expressions
This chapter assumes you know what variables are (let and const) and the basic data types like numbers and strings.
An expression is any bit of code that produces a value. 2 + 3 is an expression. So is "hi" + "!", and so is a variable like year on its own. Operators are the symbols that combine values inside expressions: +, -, ===, and so on.
Arithmetic Operators
These work on numbers:
const sum = 7 + 3; // 10 (addition)
const diff = 7 - 3; // 4 (subtraction)
const product = 7 * 3; // 21 (multiplication)
const quotient = 7 / 3; // 2.333... (division)
const remainder = 7 % 3; // 1 (remainder after division)
const power = 2 ** 3; // 8 (2 to the power of 3)The % symbol is called modulo. It gives the leftover after division: 7 divided by 3 is 2 with 1 left over. It is handy for checking if a number is even: n % 2 === 0 means even.
Strings and the + Operator
With strings, + glues text together. This is called concatenation:
const greeting = "Hello, " + "world"; // "Hello, world"
const age = 30;
const line = "Age: " + age; // "Age: 30"JavaScript also converts the number 30 into text for you here. Be careful though: "5" + 5 gives "55", not 10. When one side is a string, + joins instead of adds. For cleaner code, use a template literal instead:
const name = "Sam";
console.log(`Welcome back, ${name}!`);Backticks (` `) and ${...}` place values inside text without the plus signs.
Comparison and Boolean Operators
Comparisons produce a boolean value (true or false):
| Operator | Meaning | Example | Result |
|---|---|---|---|
| `===` | strictly equal | `5 === 5` | `true` |
| `!==` | strictly not equal | `5 !== 3` | `true` |
| `>` | greater than | `7 > 3` | `true` |
| `<` | less than | `2 < 1` | `false` |
| `>=` | greater or equal | `7 >= 7` | `true` |
Strictly equal means same value and same type. "5" === 5 is false because one is text and one is a number. Prefer === over the looser ==, which converts types and often surprises you.
Boolean operators combine true/false values:
const isAdult = age >= 18; // true or false
const canEnter = isAdult && hasTicket; // AND: both must be true
const isWeekend = isSaturday || isSunday; // OR: either is enough
const notAdult = !isAdult; // NOT: flips the valueCombining Operators
You can build bigger expressions, and parentheses control the order:
const total = (2 + 3) * 4; // 20, not 14
const label = `Total: ${2 + 3 * 4}`; // "Total: 14" (multiplication first)Multiplication binds more tightly than addition, just like in math class. When in doubt, add parentheses — they cost nothing and make your intent clear.
Exercise
What does the expression 10 % 3 evaluate to, and why?
Show answer
1. Modulo returns the remainder after division: 10 divided by 3 is 3 with 1 left over.
Exercise
What is the value of "Total: " + 2 + 2?
Show answer
"Total: 22". Once the first + makes a string, the second + joins instead of adds.
Spotted a mistake, or code that does not work?