Comparison pitfalls
Learn the difference between === and == and type coercion pitfalls.
Strict equality === and loose equality ==
JavaScript has two equality operators. === is strict equality: it compares both value and type. == is loose equality: it performs type coercion to match types and can produce surprising results.
5 === 5 // true
5 === "5" // false (number vs string)
5 == "5" // true (string is converted to number)Modern JavaScript recommends always using ===; it avoids unexpected conversions.
Type coercion pitfalls
The == operator can produce unexpected results. Here are common pitfalls:
0 == false // true
"" == false // true
null == undefined // true
"0" == false // trueThese cases confuse anyone reading the code. With === no conversion happens and the comparison is clear: 0 === false returns false.
Exercise Compare with strict equality
The userInput variable is a string. Compare it to the number 5 with strict equality (===). If they are equal, log 'Number is 5' with console.log; otherwise log 'Number is not 5'. Use if, else and ===.
Show example solution
let userInput = "5";
if (userInput === 5) {
console.log("Number is 5");
} else {
console.log("Number is not 5");
}
Test yourself
-
What is the result of "5" == 5?
- false
- true
- Throws an error
- Returns undefined
Show answer
true — Correct. == is loose equality; the string '5' is converted to a number and 5 == 5 is true.
-
Compare with strict equality
let input = "5"; if (input ____ 5) { console.log("Equal"); }Show answer
let input = "5"; if (input === 5) { console.log("Equal"); } -
Match the comparison operators
- ===
- Strict equality (type + value)
- ==
- Loose equality (with coercion)
- !==
- Strict inequality
- !=
- Loose inequality