TypeScript Comparison Operators
Comparison operators are used to compare two values. They return a boolean value (true or false) based on the result of the comparison. These operators are essential for making decisions in your code, such as in if statements.
List of Comparison Operators
- Equal to (
==) - Not equal to (
!=) - Strict equal to (
===) - Strict not equal to (
!==) - Greater than (
>) - Less than (
<) - Greater than or equal to (
>=) - Less than or equal to (
<=)
Equal to (==)
Checks if two values are equal. It does not compare data types.
Example:
console.log(5 == '5'); // true (values are the same, types are ignored)
console.log(5 == 3); // falseNot equal to (!=)
Checks if two values are not equal. It does not compare data types.
Example:
console.log(5 != '5'); // false (values are the same, types are ignored)
console.log(5 != 3); // trueStrict equal to (===)
Checks if two values are equal and also ensures their data types are the same.
Example:
console.log(5 === '5'); // false (different types: number vs string)
console.log(5 === 5); // trueStrict not equal to (!==)
Checks if two values are not equal or their data types are not the same.
Example:
console.log(5 !== '5'); // true (different types: number vs string)
console.log(5 !== 5); // falseGreater than (>)
Checks if the first value is greater than the second value.
Example:
console.log(5 > 3); // true
console.log(3 > 5); // falseLess than (<)
Checks if the first value is less than the second value.
Example:
console.log(3 < 5); // true
console.log(5 < 3); // falseGreater than or equal to (>=)
Checks if the first value is greater than or equal to the second value.
Example:
console.log(5 >= 5); // true
console.log(5 >= 3); // true
console.log(3 >= 5); // falseLess than or equal to (<=)
Checks if the first value is less than or equal to the second value.
Example:
console.log(3 <= 5); // true
console.log(5 <= 5); // true
console.log(5 <= 3); // falseSummary
Comparison operators are powerful tools in TypeScript that let you evaluate conditions and make decisions in your code. Using strict operators (=== and !==) is often recommended to avoid unexpected results due to type conversion.