Shelf shows a badge with the number of books on loan. One day the badge stops loading and stays empty. A test expects the badge to show 0, and it still passes.
const badgeText = "";
console.log(badgeText == 0);
console.log(badgeText === 0);
true
false
JavaScript has two ways to ask whether two values are the same.
== is loose equality. When the two sides have different kinds, it converts one of them first. An empty string converts to the number 0, so the first line prints true.
=== is strict equality. It converts nothing. A string and a number are never strictly equal, so the second line prints false.
A few more cases show the pattern:
console.log("3" == 3);
console.log("3" === 3);
console.log(null == undefined);
console.log(null === undefined);
true
false
true
false
Use === in test code, and !== for "not the same". With strict equality, a broken page that returns the wrong kind of value fails the check.
The assertion libraries make the same choice. In Playwright, expect(value).toBe(3) does not convert types, so the string "3" fails it.
Greater and smaller
<, >, <= and >= compare order. They work as you expect on two numbers. On two strings, they compare one character at a time, like words in a dictionary.
console.log("10" < "9");
console.log(Number("10") < Number("9"));
true
false
The character 1 comes before the character 9, so the string "10" counts as smaller. A test that checks "prices are sorted from low to high" on page text hits exactly this. Convert each price to a number before you compare.
Values that count as false
An if accepts any value, not only true and false. JavaScript treats a few values as false. The ones you will meet are false, 0, "", null, undefined and NaN. These are called falsy. Almost every other value counts as true.
console.log(Boolean(0));
console.log(Boolean(""));
console.log(Boolean("0"));
console.log(Boolean("false"));
false
false
true
true
Boolean() shows how a condition sees a value. The last two lines surprise people. "0" and "false" are strings with characters in them, so they count as true.
This is why if (badgeText) is a weak check. It is false for an empty badge, and it is true for a badge that says "Error".
Remember this
Compare with === and !==. Convert page text to a number before you compare order. A condition treats 0, "", null, undefined and NaN as false, and any other string as true.
Reference: Equality comparisons and sameness on MDN.