Skip to main content

Comparison Operators

Comparison operators are used to compare values in Typescript. These operators return a boolean value true or false. They can be used in decision-making processes, like in conditional statements such as if statements.

Basic Comparison Operators

There are six basic comparison operators in Typescript:

  1. ==: Equal to
  2. !=: Not equal to
  3. ===: Strictly equal to
  4. !==: Strictly not equal to
  5. >: Greater than
  6. <: Less than
  7. >=: Greater than or equal to
  8. <=: Less than or equal to

Let's look at each of these operators in detail.

Equal to (==)

The == operator compares the values of two operands without considering their type. If the values are equal, it returns true; otherwise, it returns false.

console.log(5 == 5); // Output: true
console.log('5' == 5); // Output: true

Not equal to (!=)

The != operator compares the values of two operands without considering their type. If the values are not equal, it returns true; otherwise, it returns false.

console.log(5 != 4); // Output: true
console.log('5' != 5); // Output: false

Strictly equal to (===)

The === operator, unlike ==, compares both the value and the type of the operands. If both are equal, it returns true; otherwise, it returns false.

console.log(5 === 5); // Output: true
console.log('5' === 5); // Output: false

Strictly not equal to (!==)

The !== operator, unlike !=, compares both the value and the type of the operands. If both are not equal, it returns true; otherwise, it returns false.

console.log(5 !== 4); // Output: true
console.log('5' !== 5); // Output: true

Greater than (>)

The > operator checks if the value of the left operand is greater than the value of the right operand. If it is, it returns true; otherwise, it returns false.

console.log(10 > 5); // Output: true
console.log(5 > 10); // Output: false

Less than (<)

The < operator checks if the value of the left operand is less than the value of the right operand. If it is, it returns true; otherwise, it returns false.

console.log(5 < 10); // Output: true
console.log(10 < 5); // Output: false

Greater than or equal to (>=)

The >= operator checks if the value of the left operand is greater than or equal to the value of the right operand. If it is, it returns true; otherwise, it returns false.

console.log(10 >= 10); // Output: true
console.log(5 >= 10); // Output: false

Less than or equal to (<=)

The <= operator checks if the value of the left operand is less than or equal to the value of the right operand. If it is, it returns true; otherwise, it returns false.

console.log(5 <= 10); // Output: true
console.log(10 <= 5); // Output: false

Conclusion

Comparison operators are essential in Typescript and programming in general. They allow us to compare values and make decisions based on those comparisons. Be sure to practice using these operators in your code to get comfortable with them. Happy coding!