If-Else Statements
Sure, here is the article.
Understanding If-Else Statements in TypeScript
Introduction
In any programming language, control flow statements play a vital role. They provide the ability to control the flow of code execution based on certain conditions. In typescript, one such crucial control flow statement is the if-else
statement. This tutorial will provide an in-depth understanding of if-else
statements in TypeScript.
The if
Statement
The if
statement is the most basic of all the control flow statements. It tells the program to execute a certain section of code only if a particular test evaluates to true
.
Here's the basic syntax for an if
statement:
if(condition) {
// code to be executed if condition is true
}
For example, let's say we have a variable num
and we want to check if it's positive:
let num = 10;
if(num > 0) {
console.log('Number is positive');
}
In this example, the condition checks whether num
is greater than 0. If the condition is true, it prints 'Number is positive'.
The else
Statement
The else
statement is used to introduce a new condition to execute if the if
condition is false
.
Here's how you write an if-else
statement:
if(condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Using the else
statement, we can modify our previous example to also handle the case where num
is not positive:
let num = -10;
if(num > 0) {
console.log('Number is positive');
} else {
console.log('Number is not positive');
}
The else if
Statement
For situations where you need to check more than two conditions, TypeScript provides the else if
statement.
Here is the syntax for the else if
statement:
if(condition1) {
// code to be executed if condition1 is true
} else if(condition2) {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}
Let's modify our example again to check whether num
is positive, negative, or zero:
let num = 0;
if(num > 0) {
console.log('Number is positive');
} else if(num < 0) {
console.log('Number is negative');
} else {
console.log('Number is zero');
}
Conclusion
In this tutorial, we learned about if-else
statements in TypeScript, which are a fundamental part of control flow in any programming language. Mastering them is key to writing flexible and efficient code. Try to write some code and use if-else
statements to control the flow based on different conditions. Happy coding!