Type coercion
Welcome to JavaScript's most famous minefield. Here "5" + 1 doesn't give 6, and
an innocent comparison can blow up where you least expect. The good news: once you
get the rule, you stop stepping on mines and learn to defuse them.
Coercion is the automatic conversion from one type to another that JavaScript does on its own. It can be very convenient... or very confusing if you don't understand it.
The famous case: + with strings
The + operator has a dual personality:
- If both sides are numbers, it adds.
- If either is a string, it concatenates (joins texts).
console.log(5 + 1); // 6 → addition of numbers
console.log("5" + 1); // "51" → "5" is text, so 1 is converted to "1"
But -, *, / only know about numbers
The other arithmetic operators make no sense with text, so JavaScript converts the string to a number before operating:
console.log("5" - 1); // 4 → "5" is converted to 5
console.log("5" * 2); // 10
console.log("10" / 2); // 5
That is why "5" + 1 gives "51" but "5" - 1 gives 4. The difference is in the
operator, not in the data.
⚠️ CLASSIC TRAP. This is where everyone trips: a value that arrives as text (say, whatever the user types into a form) plus a
+and, instead of adding, JavaScript glues strings together."5" + 1is"51", not6. Convert to a number yourself (withNumber(...)) before adding and save yourself the headache.
== vs ===
===(strict equality): compares value and type. It does not do coercion.==(loose equality): converts the types before comparing.
console.log(5 === "5"); // false → different type (number vs string)
console.log(5 == "5"); // true → "5" is converted to 5 before comparing
console.log(0 == ""); // true → surprising coercion
console.log(null == undefined); // true
Golden rule: always use
===and!==. They avoid surprises and make your code predictable.==is reserved for very specific cases.
You've just defused JavaScript's most famous mines. From now on, whenever you see
someone else's == or a "5" + 1, you'll know exactly what's going on, and that
already sets you apart from plenty of people who've gone years without getting it.
Examples
The + versus the other operators
console.log("5" + 1); // "51"
console.log("5" - 1); // 4
console.log("5" * 2); // 10
Strict vs loose equality
console.log(5 === "5"); // false
console.log(5 == "5"); // true