JavaScript offers robust capabilities for comparing numbers, a crucial aspect of building dynamic and responsive applications. This guide explores the fundamental techniques for effectively comparing numerical values.
Table of Contents
- Comparison Operators
- Logical Operators
- Chaining Comparisons
- Handling Special Cases (NaN, Infinity)
- Conclusion
Comparison Operators
JavaScript provides six primary comparison operators for evaluating numerical relationships. These operators return a Boolean value (true
or false
).
Operator | Description | Example | Result |
---|---|---|---|
=== |
Strict Equality (checks both value and type) | 5 === 5 |
true |
!== |
Strict Inequality | 5 !== "5" |
true |
> |
Greater Than | 10 > 5 |
true |
< |
Less Than | 5 < 10 |
true |
>= |
Greater Than or Equal To | 10 >= 10 |
true |
<= |
Less Than or Equal To | 5 <= 10 |
true |
Why Strict Equality (===
)? Using strict equality is generally recommended to prevent unexpected type coercion. The loose equality operator (==
) performs type conversion before comparison, which can lead to errors.
5 == "5"; // true (type coercion occurs)
5 === "5"; // false (strict equality; types are different)
Logical Operators
Logical operators combine multiple comparisons, creating complex conditional statements.
Operator | Description | Example | Result (if num1 = 10, num2 = 5) |
---|---|---|---|
&& |
Logical AND (both conditions must be true) | (num1 > 5) && (num2 < 10) |
true |
|| |
Logical OR (at least one condition must be true) | (num1 0) |
true |
! |
Logical NOT (inverts the Boolean value) | !(num1 === num2) |
true |
let score = 85;
if (score >= 90 && score = 80 && score < 90) {
console.log("B Grade");
} else {
console.log("Below B Grade");
}
Chaining Comparisons
For cleaner code, chain comparisons when checking if a number falls within a range:
let age = 25;
if (18 <= age && age < 65) {
console.log("Adult");
}
Handling Special Cases (NaN, Infinity)
NaN
(Not a Number) and Infinity
require special consideration:
NaN
is never equal to itself:NaN === NaN
isfalse
. UseisNaN()
to check forNaN
.Infinity
and-Infinity
have specific comparison behaviors.
isNaN(Number("hello")); // true
Infinity > 1000; // true
-Infinity < -1000; // true
Conclusion
Mastering numerical comparisons in JavaScript is fundamental for building robust applications. By effectively using comparison and logical operators, and understanding special cases, you can create highly functional and reliable code.