Checking Equality with ===
JavaScript has two operators that check if two values are equal: == and ===. They give different answers, and you should almost always use ===.
== is called loose equality. Before it compares, it changes both values to the same type:
console.log("5" == 5);
console.log(0 == "");
console.log(0 == false);
Output:
true
true
true
The text "5" is equal to the number 5. Zero is equal to empty text, and also to false. These changes follow rules, but the rules are long and hard to remember. If your code uses == and a value arrives with an unexpected type, the code does not fail. It quietly gives a wrong answer, and that kind of bug is hard to find.
=== is called strict equality. It never changes types. Two values with different types are never equal:
console.log("5" === 5);
console.log(5 === 5);
console.log("5" !== 5);
Output:
false
true
true
!== means "not equal", and it is strict too. Always use === and !==. Most JavaScript programmers follow this rule.
Compare as text, or as numbers
Sometimes you do want to compare values of different types. Then convert them yourself first. This also shows the reader what you meant:
const a = "07";
const b = "7";
console.log(a === b);
console.log(Number(a) === Number(b));
Output:
false
true
As text, "07" and "7" are different strings. As numbers, both are 7. So whether two values are "equal" depends on what you compare them as, and === with Number lets you choose.
=== is also how you check for null, as promised in the booleans lesson:
const prize = null;
console.log(prize === null);
Output:
true
You may see one use of == in other people's code: x == null. It is true when x is null or undefined. Some teams allow this, and some do not. In this course, use ===.
In the exercise, read two lines and compare them as text and as numbers.