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:
==
: Equal to!=
: Not equal to===
: Strictly equal to!==
: Strictly not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: 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!