1.2. Checking Equality or Comparing Values
Problem
You want to check if two values are equal.
Solution
Use the equality (or inequality) or strict
equality (or strict inequality) operator to compare two values. To
check whether a value is a valid number, use isNaN(
).
Discussion
Equality expressions always return a Boolean value indicating whether the two values are equal. The equality (and inequality) operators come in both regular and strict flavors. The regular equality and inequality operators check whether the two expressions being compared can be resolved to the same value after converting them to the same datatype. For example, note that the string “6” and the number 6 are considered equal because the string “6” is converted to the number 6 before comparison:
trace(5 == 6); // Displays: false trace(6 == 6); // Displays: true trace(6 == "6"); // Displays: true trace(5 == "6"); // Displays: false
The logical inequality operator (!=) returns false
if two values are equal and true if they are not equal. If necessary,
the operands are converted to the same datatype before the
comparison:
trace(5 != 6); // Displays: true trace(6 != 6); // Displays: false trace(6 != "6"); // Displays: false trace(5 != "6"); // Displays: true
On the other hand, the strict equality and inequality operators first check whether the values being compared are of the same datatype before performing the comparison. Differences in datatype cause the strict equality operator to return false and the strict inequality ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access