1.9 — Type coercion & comparison
Every lesson so far kept the types apart. Time for the collision: what happens when a string and a number meet at the same operator? The machine never stops to ask — it silently converts one of them and carries on. That silent conversion is called coercion, and it’s behind some of the most famous “JavaScript is weird” screenshots on the internet — and behind very real bugs you’ll be paid to catch. Today the weirdness becomes predictable.
console.log("5" + 5);
console.log("5" - 5);
console.log(5 == "5");
console.log(5 === "5");Line 1: "5" + 5. A string (teal) and a number (yellow) drop into the + machine. Two different types, one operator. The machine must make them match before it can work — and it will NOT ask your permission.
The deeper story, with the real names for things — this part is what turns “I saw it” into “I can explain it.”
The conversion cheat sheet: + prefers strings — one string infects the whole operation, gluing wins.
−, *, / and % prefer numbers instead — strings get converted. If the conversion fails ("abc" * 2), you get NaN: the “math lost all meaning” value from lesson 1.5.
Comparison with == follows a genuinely strange rulebook. Programmers keep actual lookup tables for it. That is the argument for never using it: a comparison you need a table to predict is a comparison you cannot trust at a glance.
💼 On the job — this one will bite you as an automation tester: everything typed into a form arrives as a string (lesson 1.1 called it). So age + 1, where age came from an input field, is "25" + 1 → "251" — a birthday bug, silently.
The fix is explicit conversion — coercion you control: Number("25") → 25, String(25) → "25". Explicit conversion is honest and easy to search for. Implicit coercion is a surprise waiting to happen. Prefer the honest kind.
Also in the family: != is loose not-equals (same liar, negated) and !== is the strict one you’ll actually use.
Real projects enforce this automatically — a linter (ESLint, Phase 8) flags every == the instant it is typed.
✏️ Quick check 1
Type exactly what console.log("10" + 1) shows:
✏️ Quick check 2
And console.log("10" - 1)? Type it:
✏️ Quick check 3
status holds the NUMBER 200. Type what status == "200" (loose, double =) evaluates to — then read why that answer is dangerous in a test.
🗣️ Now teach it back
Explain to a friend: what is coercion, why does "5" + 5 give "55" but "5" - 5 give 0, and why should they always write === instead of ==?
Write it as if your friend is sitting next to you. Saved to your journal — future-you will use these notes to teach others.