Typescript else statement
Created By: chatGPT
TypeScript provides the ability to control the flow of execution in your code using conditional statements, such as
if
and else
. The else
statement allows you to define a block of code that will execute when the if
condition evaluates to false
. Here's a basic example to illustrate its use.let age: number = 18;
if (age >= 18) {
console.log('You are an adult.');
} else {
console.log('You are a minor.');
}
In the example above, if the variable
age
is greater than or equal to 18, the program will log 'You are an adult.'. If age
is less than 18, it will log 'You are a minor.'. The else
block can help you handle alternative scenarios in your code.let temperature: number = 30;
if (temperature > 25) {
console.log('It is warm outside.');
} else {
console.log('It is cold outside.');
}
Multiple Conditions can also be handled using
else if
statements. This allows you to check multiple conditions sequentially.let score: number = 75;
if (score >= 90) {
console.log('Grade: A');
} else if (score >= 80) {
console.log('Grade: B');
} else if (score >= 70) {
console.log('Grade: C');
} else {
console.log('Grade: F');
}
In the grade example above, the program checks the score variable against multiple thresholds using
else if
. This makes it easy to determine the appropriate grade based on the score. Each conditional check will stop executing further checks once a match is found.let num: number = 0;
if (num > 0) {
console.log('Positive');
} else if (num < 0) {
console.log('Negative');
} else {
console.log('Zero');
}