Comparing Values with === and Other Operators
Introduction
Welcome back! We have learned that values can have different types and that we can convert between text and numbers when a calculation needs it. Now we can compare values to ask questions such as whether stock is below a reorder level.
In this lesson, we will use comparison operators to produce booleans, store those answers, and check equality with === and !==. We will also see why the loose equality operator == can give a surprising result.
A Comparison Produces a Boolean
A comparison checks a relationship between two values and produces a boolean: true when the relationship holds, or false when it does not. For example, we can check whether a stock count is below a reorder level:
The first question is true because 4 is below 10. The second question is false because 4 is not greater than or equal to 10. When the program runs, we see:
The symbols < and >= compare numbers here. We can use > for greater than, < for less than, >= for greater than or equal to, and <= for less than or equal to. For example, stockCount <= reorderLevel is true when the stock count is 10 or less.
Store a Comparison Result
A comparison's boolean result is a value just like a number or string. We can store it in a variable and use it later:
JavaScript checks the comparison on the right side of =, stores the result under needsReorder, and then prints its value and type:
The name needsReorder describes the question we asked. Clear names become especially helpful when a boolean will be used in several places.
Check Whether Values Match
For the simple values in this lesson, we use three equals signs, ===, to check that both the value and type match without converting one side. To check that they differ, we use !==:
The first two comparisons are true. The last is false because the number 4 and the string "4" have different types:
This strict comparison is useful because it does not silently convert one type to match the other. In this path, === is the equality operator we use in our own code, and !== is its opposite.
