Why is === better than ==?
Why double equals can "coerce types", where strict comparison hides without ===, and how % trips on negative numbers.
== and ===. Beginners write the first — it's shorter. Experienced developers almost always write the second. You're about to see why.console.log(5 == "5");
console.log(5 === "5");
console.log(0 == "");
console.log(null == undefined);
console.log(0 === "");== is ready to call very different things equal.=== (strict equality) compares both type and value: the number 5 and the string "5" are different.
== (loose) first tries to coerce the values to one type, then compares. The coercion rules are long and unobvious: 0 == "" is true, "0" == false is true, yet "" == "0" is false. Remembering them all is nearly impossible.
Why is that dangerous? Form data arrives as strings. The comparison quantity == 0 is true both for 0 and for an empty string when the user typed nothing — and the program mistakes an empty field for "zero items". Strict === won't let that confusion happen: if the types differ, the answer is false straight away.
Strict comparison also hides where no === is written. switch compares the value with each case using exactly ===. So the string "2" won't match case 2, even though it looks the same.
function zone(floor) {
switch (floor) {
case 1:
return "dance floor";
case 2:
return "VIP";
default:
return "no such floor";
}
}
console.log(zone(2));
console.log(zone("2"));
console.log(zone(Number("2")));That's not an oversight, it's honesty: switch doesn't guess what you meant. The bug shows up at once — the guest from floor "2" landed in default. With == it would quietly work until the day an empty string arrived.
The remainder % has a comparison trap of its own. An odd number is one whose remainder after dividing by 2 isn't zero. It's tempting to check n % 2 === 1. But in JavaScript the sign of % comes from the dividend: -3 % 2 is -1, not 1.
function isOddWrong(n) {
return n % 2 === 1;
}
function isOdd(n) {
return n % 2 !== 0;
}
console.log(-3 % 2);
console.log(isOddWrong(-3), isOdd(-3));
console.log(isOddWrong(5), isOdd(5));Where does this bite in practice? The temperature outside, an account balance, an offset on a map — negative numbers show up more often than you'd think. A % 2 === 1 check will silently call -3 even, and you'll never see an error.
See the common thread? A good comparison answers one question honestly and doesn't pretend to understand you better than what you wrote. === doesn't coerce types, switch doesn't turn a string into a number, % 2 !== 0 doesn't care about the sign. The less a comparison “guesses”, the sooner you see the bug — on your own screen, not the user's.
Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.