TypeScript comparison operators are the same as JavaScript. Comparison operators help in comparing two variables by their values.
Please note that some operators use type coercion while comparing the values, while some do not. Please use them carefully.
Type coercion means that when the operands of an operator are different types, one of them will be converted to an “equivalent” value of the other operand’s type. For example,
100 == "100" //true 100 === "100" //false
1. Comparison Operators
Operator | Description |
---|---|
== |
let firstVar = 10; let secondVar = 20; console.log( firstVar == secondVar ); //false console.log( firstVar == '10' ); //true console.log( 10 == '10' ); //true |
=== |
let firstVar = 10; let secondVar = 20; console.log( firstVar === secondVar ); //false console.log( firstVar === 10 ); //true console.log( firstVar === '10' ); //false console.log( 10 === '10' ); //false |
!= |
let firstVar = 10; let secondVar = 20; console.log( firstVar != secondVar ); //true console.log( firstVar != 10 ); //false console.log( firstVar != '10' ); //false |
!== |
let firstVar = 10; let secondVar = 20; console.log( firstVar !== secondVar ); //true console.log( firstVar !== 10 ); //false console.log( firstVar !== '10' ); //true |
> |
Checks if the value of the left operand is greater than the value of the right operand. This operator uses type coercion.
let firstVar = 10; let secondVar = 20; console.log( firstVar > secondVar ); //false console.log( firstVar > 10 ); //false console.log( firstVar > '10' ); //false |
< |
Checks if the value of the left operand is less than the value of the right operand. This operator uses type coercion.
let firstVar = 10; let secondVar = 20; console.log( firstVar < secondVar ); //true console.log( firstVar < 10 ); //false console.log( firstVar < '10' ); //false |
>= |
Checks whether the value of the left operand is greater than or equal to the value of the right operand. This operator uses type coercion.
let firstVar = 10; let secondVar = 20; console.log( firstVar >= secondVar ); //false console.log( firstVar >= 10 ); //true console.log( firstVar >= '10' ); //true |
<= |
Checks whether the value of the left operand is less than or equal to the value of the right operand. This operator uses type coercion.
let firstVar = 10; let secondVar = 20; console.log( firstVar <= secondVar ); //true console.log( firstVar <= 10 ); //true console.log( firstVar <='10' ); //true |
Happy Learning !!