ILILCode

Operators: math, comparison and logic

Arithmetic, strict equality, && and ||, and the nullish coalescing operator that saves defaults.

Lesson 3 of 23 in JavaScript9 min1 exercise

Arithmetic works the way you expect, with two additions: % gives the remainder and ** raises to a power.

Arithmetic
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 !==.

Comparison
1 == "1";   // true  (avoid)
1 === "1";  // false (use this)
2 > 1;      // true
2 >= 2;     // true
"abc" === "abc"; // true

Logic 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.

Three ways to say "or"
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"; // ternary

Try it

Run it, then break it on purpose

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

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.

exercise.js
console · run your code or check the answer