Comparison operators are used in logical statements to determine equality or difference between variables or values. The result of a comparison is always a boolean value: true or false.
Here are the comparison operators available in JavaScript:
| Operator | Description | Example |
|---|---|---|
== |
Equal to (checks value only) | x == 8 |
=== |
Strict equal to (checks value and type) | x === "8" |
!= |
Not equal to | x != 8 |
!== |
Strict not equal to | x !== "8" |
> |
Greater than | x > 8 |
< |
Less than | x < 8 |
>= |
Greater than or equal to | x >= 8 |
<= |
Less than or equal to | x <= 8 |
The most important part of comparison in JavaScript is understanding the difference
between == and ===.
The == operator compares two values for equality after converting
them to a common type (type coercion).
let x = 5;
console.log(x == 5); // true
console.log(x == "5"); // true (string "5" is converted to number 5)
The === operator (also called "identity" or "triple equal") compares both
the value and the data type. No conversion happens.
let x = 5;
console.log(x === 5); // true
console.log(x === "5"); // false (because one is a number and the other is a string)
=== and !==. They are
more predictable and prevent hidden bugs caused by automatic type conversion.
These operators are used to compare numeric values (though they also work with strings using alphabetical order).
let age = 18;
console.log(age > 15); // true
console.log(age < 20); // true
console.log(age >= 18); // true
console.log(age <= 10); // false
Comparison operators are most commonly used inside if statements to control
the flow of the program.
let hour = 14;
if (hour < 18) {
console.log("Good day!");
}
true or false== compares values only; === compares values and types>, <, etc.) are standard math comparisons