AI Hints
Home›JavaScript Tutorial›Comparing Values
JavaScript · Lesson 14 of 138

Type Coercion

Why === beats ==.

⏱ 2 min read▶ Video at 15:29🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Type Coercion
From the video: Type Coercion
  • 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.

app.jsjavascript
console.log(5 + "5");
console.log("10" - 3);
console.log(0 == "");
console.log(0 === "");
console.log("1" == 1, "1" === 1);
Output
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.

keyvalue
5 + '5''55'
'10' − 37
0 == ''true, surprise
Rulealways ===

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 ===
Next up: null and undefined — nothing, two ways