Operators and expressions
An expression is any piece of code that produces a value, like 2 + 3 or age >= 18. Operators are the symbols that combine values.
Arithmetic
The remainder operator % is surprisingly useful. For example, n % 2 === 0 tells you whether n is even.
Shortcuts
Comparison
Comparisons produce a boolean (true or false).
Always use
===and!==. The loose versions==and!=convert types behind your back, which causes confusing bugs.
Logical operators
| Operator | Meaning | Example |
|---|---|---|
&& |
AND: both must be true | age >= 18 && hasTicket |
|| |
OR: at least one is true | isAdmin || isOwner |
! |
NOT: flips true/false | !isLoggedIn |
Truthy and falsy
In a true/false situation, JavaScript treats some values as false. These are the falsy values: false, 0, '' (an empty string), null, undefined and NaN. Everything else is truthy, including '0', [] and {}.
Default values with ?? and ||
Operator precedence
Multiplication happens before addition, just like in maths. Use brackets to be explicit.
Practice
A shop gives a 10% discount when the total is over 100. Given price and qty, print the final amount. Then print whether qty is even.
1.What is 17 % 5?
2.What does 0 ?? 10 return?