Comparison operators are symbols or combinations of symbols that allow us to compare two values and determine whether a specific condition is true or false.
These operators are widely used in control structures like conditionals and loops to make decisions based on value comparisons.
The most common comparison operators are,
| Operator | Example | Result |
|---|---|---|
| Equal (==) | 5 == 5 | true |
| Not Equal (!=) | 3 != 7 | true |
| Greater than (>) | 10 > 5 | true |
| Less than (<) | 2 < 8 | true |
| Greater than or equal to (>=) | 7 >= 7 | true |
| Less than or equal to (<=) | 4 <= 4 | true |
As we said, these operators return a boolean value (true or false) based on the comparison result.
- Equal
==: compares if two values are equal. - Not Equal
!=: compares if two values are different. - Greater than
>: compares if the left value is greater than the right value. - Less than
<: compares if the left value is less than the right value. - Greater than or equal to
>=: compares if the left value is greater than or equal to the right value. - Less than or equal to
<=: compares if the left value is less than or equal to the right value.
Using Comparison Operators in Programming Languages
The use of these operators is basically the same in all programming languages. Next, we will see how to use comparison operators in different programming languages:
For example, this is how it would be in C, C++, C# or Java
int a = 5;
int b = 10;
bool equal = (a == b); // equal = false
bool notEqual = (a != b); // notEqual = true
bool greaterThan = (a > b); // greaterThan = false
bool lessThan = (a < b); // lessThan = true
bool greaterOrEqual = (a >= b); // greaterOrEqual = false
bool lessOrEqual = (a <= b); // lessOrEqual = true
It would be very similar in the case of JavaScript, with the exception of variable declaration using let
let a = 5;
let b = 10;
let equal = (a == b); // equal = false
let notEqual = (a != b); // notEqual = true
let greaterThan = (a > b); // greaterThan = false
let lessThan = (a < b); // lessThan = true
let greaterOrEqual = (a >= b); // greaterOrEqual = false
let lessOrEqual = (a <= b); // lessOrEqual = true
Similarly in Python
a = 5
b = 10
equal = (a == b) # equal = False
notEqual = (a != b) # notEqual = True
greaterThan = (a > b) # greaterThan = False
lessThan = (a < b) # lessThan = True
greaterOrEqual = (a >= b) # greaterOrEqual = False
lessOrEqual = (a <= b) # lessOrEqual = True
In the examples,
- We have declared two integer variables
aandb - Then, we used the comparison operators to compare the values of the variables
- We stored the result in boolean variables
