Type Coercion
Why === beats ==.
JavaScript tries to be helpful. When you mix types, like a number and a string, it quietly converts one of them. That's called type coercion. Sometimes it helps. Often, it surprises you.

- JavaScript converts types
- Type coercion
- Often surprising
Surprises
Five plus the string five gives the string fifty five, because plus joins strings. But minus has no string meaning, so it converts to numbers. Two equals converts types before comparing, so the number zero equals an empty string. Three equals doesn't convert, so it says false. Run it.
console.log(5 + "5");
console.log("10" - 3);
console.log(0 == "");
console.log(0 === "");
console.log("1" == 1, "1" === 1);55 7 true false true false
The rule
Always use three equals, and exclamation equals equals. They compare values without converting types, so there are no surprises. And when you need to mix numbers and strings, convert them yourself, on purpose. We'll see how in a couple of lessons.
| key | value |
|---|---|
| 5 + '5' | '55' |
| '10' − 3 | 7 |
| 0 == '' | true, surprise |
| Rule | always === |
Summary
JavaScript converts types when you mix them, which can surprise you. Always use three equals. Next, two kinds of nothing, null and undefined.
Key takeaways- + joins strings
- == converts types
- Use ===