TypeScript - If...else Statement
Introduction
The if...else statement is used to execute one block of code if a condition is true, and another block of code if the condition is false. It helps in controlling the flow of the program based on conditions.
Syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}- The condition is an expression that evaluates to either
trueorfalse. - If the condition is
true, the code inside theifblock is executed. - If the condition is
false, the code inside theelseblock is executed.
Example 1: Simple If-else
let number = 10;
if (number > 5) {
console.log("Number is greater than 5.");
} else {
console.log("Number is less than or equal to 5.");
}Output:
Number is greater than 5.Example 2: If-else with Comparison Operators
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}Output:
You are an adult.Example 3: If-else with Boolean Expression
let isRaining = false;
if (isRaining) {
console.log("Don't forget your umbrella!");
} else {
console.log("You can leave your umbrella at home.");
}Output:
You can leave your umbrella at home.Conclusion
The if...else statement is a fundamental control structure in TypeScript that allows you to execute different blocks of code depending on the truthiness of a condition. It is used in almost all programming scenarios where a decision needs to be made based on certain conditions.