Overview and Lesson Plan

Greetings, Explorer! Today, our exploration takes us to TypeScript Comparison Operators. Much like in real life, our code often needs to make decisions based on comparisons. Our voyage today will elucidate how comparison operators in TypeScript compare values, thus forming the basis for decision-making tools.

Introduction to TypeScript Comparison Operators

Life and programming both involve a lot of comparisons, and TypeScript is no exception. TypeScript comparison operators, which are similar to JavaScript's, include ==, !=, ===, !==, >, <, >=, <=. Let's dive straight into an example:

let number5: number = 5;
let number10: number = 10;

console.log(number5 == number10); // false, because 5 is not equal to 10
console.log(number5 === number10); // false, because 5 is not equal to 10
console.log(number5 != number10); // true, because 5 is indeed not equal to 10
console.log(number5 !== number10); // true, because 5 is indeed not equal to 10
console.log(number5 > number10); // false, because 5 is not greater than 10
console.log(number5 < number10); // true, because 5 is less than 10
console.log(number5 >= number10); // false, because 5 is neither greater than nor equal to 10
console.log(number5 <= number10); // true, because 5 is less than or equal to 10

The provided example covers all comparison operators, and we are going to break down some of them in the forthcoming sections for a detailed understanding.

Diving Deep into TypeScript Comparison Operators

In this deep dive, we’ll pay close attention to the differences between double equals (==) and triple equals (===), and not equals (!=) and not strictly equals (!==) operators.

  • Equal to (==) and Not equal to (!=) - These operators consider only the value, while ignoring the type.
console.log(5 == <any>"5"); // true, as the value 5 matches with the string "5", even when the types are different
console.log(5 != <any>"5"); // false, due to matching values
  • Strictly equal to (===) and Not strictly equal to (!==) - These operators take into account both the type and the value.
console.log(5 === <any>"5"); // false, due to mismatch in types (number and string)
console.log(5 !== <any>"5"); // true, as their types and values don't match

As evident, === and !== guarantee a robust check, ensuring that the compared variables share the same value and type. Understanding these nuances is a critical skill in decision-making processes!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal