Operators: math, comparison and logic
Arithmetic, strict equality, && and ||, and the nullish coalescing operator that saves defaults.
Arithmetic works the way you expect, with two additions: % gives the remainder and ** raises to a power.
7 + 2; // 9
7 - 2; // 5
7 * 2; // 14
7 / 2; // 3.5
7 % 2; // 1 (remainder)
7 ** 2; // 49 (power)Equality: always use ===
== converts types before comparing, so 1 == "1" is true and "" == 0 is true. === compares value and type. In every codebase you touch, use === and !==.
1 == "1"; // true (avoid)
1 === "1"; // false (use this)
2 > 1; // true
2 >= 2; // true
"abc" === "abc"; // trueLogic and defaults
&& returns the first falsy value, || the first truthy one. That makes || handy for defaults — but it also replaces 0 and "". Use ?? when only null and undefined should trigger the fallback.
const a = 0;
a || "fallback"; // "fallback" (0 is falsy)
a ?? "fallback"; // 0 (only null/undefined fall back)
a > 5 && "big"; // false
const label = a > 5 ? "big" : "small"; // ternaryTry it
Run it, then break it on purpose
Exercises
Checked in your browser · hints and solutions included
Exercise
Who can vote?
Write canVote(age, isCitizen) that returns true only when the person is 18 or older and is a citizen. It always returns a boolean.
canVote(18, true) → true; canVote(17, true) → false; canVote(30, false) → false.