DevPath · Learn to code ESPTEN

Operators and coercion

Type coercion: == vs ===

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:

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" + 1 is "51", not 6. Convert to a number yourself (with Number(...)) before adding and save yourself the headache.

== vs ===

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
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Comparison and logical operatorsView the module →