Language: EN

programacion-operadores-comparacion

Comparison Operators

Comparison operators are symbols or combinations of symbols that allow us to compare two values and determine if a certain condition is true or false.

These operators are widely used in control structures such as conditionals and loops to make decisions based on value comparisons

The most common comparison operators are,

OperatorExampleResult
Equal (==)5 == 5true
Not equal (!=)3 != 7true
Greater than (>)10 > 5true
Less than (<)2 < 8true
Greater than or equal to (>=)7 >= 7true
Less than or equal to (<=)4 <= 4true

As we have said, these operators return a boolean value (true or false) depending on the result of the comparison.

  • Equal ==: compares if two values are equal.
  • Not equal !=: compares if two values are different.
  • Greater than >: compares if the value on the left is greater than the value on the right.
  • Less than <: compares if the value on the left is less than the value on the right.
  • Greater than or equal to >=: compares if the value on the left is greater than or equal to the value on the right.
  • Less than or equal to <=: compares if the value on the left is less than or equal to the value on the right. Here is an example table with results to show their usage.

Using comparison operators in programming languages

The use of the 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 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 the variable declaration with 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

Just like 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 a and b. Then, we use the comparison operators to compare the values of the variables and store the result in boolean variables.