Decision Making in TypeScript

Job-ready Online Courses: Knowledge Awaits – Click to Access!

Like every other programming language, TypeScript offers several decision-making statements to regulate how a program is executed. These statements allow programmers to execute particular blocks of code by the circumstances. The different TypeScript decision-making statements, such as if-else, switch-case, for, while, do-while, and break, will be covered in this article.

One of the key features of TypeScript that facilitates decision-making is its support for conditional types. Conditional types allow developers to create types that depend on other types. For example, a conditional type might specify that a certain variable should have a different type depending on the value of another variable. This can be useful when you need to make decisions based on certain criteria, such as whether a user is logged in or not.

Decision Making in TypeScript

1. If-Else Statements:

An if-else statement is the most common style of decision-making statement in TypeScript. They allow programmers to execute specific code segments based on whether or not a condition is true. The syntax of an if-else expression is as follows:

if (condition) {
 // code to execute if the condition is true
} else {
 // code to execute if the condition is false
}

This syntax’s expression evaluated as true or false serves as the condition. The first block’s code is run if the condition is satisfied. If not, the code contained in the second block is run.

For example, consider the following TypeScript code:

let DataFlair_x = 10;
if (DataFlair_x > 5) {
 console.log('DataFlair_x is greater than 5');
} else {
 console.log('DataFlair_x is less than or equal to 5');
}

Output

DataFlair_x is greater than 5

In this instance, the if-else clause determines whether the value of DataFlair_x exceeds 5. The first code block is performed because the condition is true and the value of DataFlair_x is 10. The output will therefore be DataFlair_x higher than 5.

2. If-Else Ladder:

An If-else ladder is a series of if-else statements in TypeScript that allow you to test multiple conditions in a specific order. The ladder structure of the statements resembles a real-life ladder, where each step represents a condition that must be met before proceeding to the next step.

In an If-else ladder, the first if statement is evaluated, and if the condition is true, the code block associated with that if statement is executed. If the condition is false, the next else if statement is evaluated, and if the condition is true, the code block associated with that else if statement is executed. This process continues until either a condition is true, or the final else statement is reached.

Here is an example of an If-else ladder in TypeScript:

let DataFlair_score: number = 85;


if (DataFlair_score >= 90) {
 console.log('You got an A!');
} else if (DataFlair_score >= 80) {
 console.log('You got a B.');
} else if (DataFlair_score >= 70) {
 console.log('You got a C.');
} else if (DataFlair_score >= 60) {
 console.log('You got a D.');
} else {
 console.log('You failed.');
}

Output

You got a B.

3. Nested If-Else Statements:

A nested if-else statement in TypeScript is a way of creating multiple conditional statements inside another conditional statement. This is often used when there are multiple conditions that need to be checked before a certain action is taken.

For example, imagine you have a variable called “temperature” that represents the current temperature. You want to turn on the air conditioning if the temperature is above 80 degrees Fahrenheit, but only if the humidity is also below 70%.

You could write a nested if-else statement like this:

if (DataFlair_temperature > 80) {
 if (humidity < 70) {
   turnOnAirConditioning();
 } else {
   console.log("It's too humid to turn on the air conditioning.");
 }
} else {
 console.log("It's not hot enough to turn on the air conditioning.");
}

Output

It’s too humid to turn on the air conditioning.”)

In this example, the outer if statement checks if the DataFlair_temperature is above 80 degrees Fahrenheit. If it is, then the inner if-else statement is executed. If the humidity is below 70%, then the turnOnAirConditioning() function is called. And If the humidity is 70% or higher, then a message is printed to the console indicating that it’s too humid to turn on the air conditioning.

If the DataFlair_temperature is not above 80 degrees Fahrenheit, then the else statement is executed, and a message is printed to the console indicating that it’s not hot enough to turn on the air conditioning.

4. Switch-Case Statements:

Switch-case statements are another decision-making statement in TypeScript. It executes specific blocks of code based on the value of a variable or expression. A switch-case statement has the following syntax:

switch (expression) {
 case value1:
   // code to execute when expression matches value1
   break;
 case value2:
   // code to execute when expression matches value2
   break;
 default:
 // code to execute when none of the cases match
}

In this syntax, the variable or expression whose value is compared to the various circumstances is known as the expression. The code, in that case, is run if the expression’s value matches one of its case values. The default block’s function is run if none of the case values match.

For example, consider the following TypeScript code:

let DataFlair_day = 'Wednesday';
switch (DataFlair_day) {
 case 'Monday':
   console.log('Today is Monday');
   break;
 case 'Tuesday':
   console.log('Today is Tuesday');
   break;
 case 'Wednesday':
   console.log('Today is Wednesday');
   break;
 default:
   console.log('Today is not a weekday');
}

Output

Today is Wednesday

In this example, the switch-case statement checks the value of the DataFlair_day variable. Since the DataFlair_day’s value is “Wednesday,” the third case is matched, and the code inside that case is executed. As a result, the output will be Today, Wednesday.

Rules of Switch-case:

Here are some rules to keep in mind when using switch statements in TypeScript:

1. The variable being tested must be a primitive type or an object type that can be coerced to a primitive type (such as a string or a number).

2. Each case clause must contain a constant value or an expression that evaluates to a constant value.

3. There can be multiple case clauses that match the same value, in which case the first matching case clause will be executed.

4. The switch statement must end with a default clause, which will be executed if none of the case clauses match the value of the tested variable.

5. Each code block within a case clause must be terminated with a break statement, which tells TypeScript to exit the switch statement and continue with the next statement after the switch block.

5. For Loops:

In TypeScript, for loops are used to run a section of code repeatedly for a predetermined number of times. A for loop has the following syntax:

for (initialization; condition; increment / decrement) {
 // code to execute for each iteration
}

In this syntax, the initialization statement initializes the loop variable. The condition statement establishes the prerequisites for the loop’s continuation. The increment/decrement statement updates the loop variable after each iteration. The loop’s function is executed at each iteration if the condition is true.

For example, consider the following TypeScript code:

for (let DataFlair_i = 0; DataFlair_i < 5; DataFlair_i++) {
 console.log(DataFlair_i);
}

Output

0
1
2
3
4

In this example, the for loop initializes the loop variable DataFlair_i to 0, checks if DataFlair_i is less than 5 and increments DataFlair_i by 1 after each iteration. The loop is executed five times, and the output will be the values of DataFlair_i from 0 to 4.

6. While Loops:

While loops are used in TypeScript to repeatedly run a block of code while a predetermined condition is true, and their syntax is as follows:

while (condition) {
 // code to execute for each iteration
}

The conditional statement is assessed before each iteration in this syntax.
The loop’s code is run if the condition is satisfied. The loop is ended if the condition is false.

For example, consider the following TypeScript code:

let DataFlair_i = 0;
while (DataFlair_i < 5) {
 console.log(DataFlair_i);
 DataFlair_i++;
}

Output

0
1
2
3
4

In this illustration, the while loop checks to see if the value of DataFlair_i is less than 5 before each iteration. If the condition is true, the function inside the loop is run, and DataFlair_i is raised by 1. The output is a range of DataFlair_i values five times through the loop from 0 to 4.

7. Do-While Loops:

While loops and do-while loops are similar, the condition is only tested after executing the code. This means that even if the condition is false, the function inside the loop is always run at least once. The syntax of a do-while loop is as follows:

do {
 // code to execute for each iteration
} while (condition);

In this syntax, the code inside the loop is executed first, then the condition statement is evaluated. If the test is successful, the loop is repeated. The loop is ended if the condition is false.

For example, consider the following TypeScript code:

let DataFlair_i = 0;
do {
 console.log(DataFlair_i);
 DataFlair_i++;
} while (DataFlair_i < 5);

Output

0
1
2
3
4

In this example, the do-while loop executes the code inside the loop at least once, even though the value of DataFlair_i is initially 0 and the condition is false. After the first iteration, the condition is checked. The loop is executed four more times until the value of DataFlair_i is 5. The output will be the values of DataFlair_i from 0 to 4.

8. Break Statements:

To end a loop or switch-case statement before it reaches its natural finish, TypeScript uses break statements. The program immediately ends the loop or switch-case statement when a break statement is found inside of one. Outside of the loop or switch-case statement, control is passed to the following statement.

For example, consider the following TypeScript code:

for (let DataFlair_i = 0; DataFlair_i < 5; DataFlair_i++) {
 if (DataFlair_i === 3) {
   break;
 }
 console.log(DataFlair_i);
}

Output

0
1
2

In this example, the for loop executes five times, but when the value of DataFlair_i is 3, the if statement is true, and the break statement is executed. As a result, the loop is terminated, and the output will be the values of DataFlair_i from 0 to 2.

Conclusion:

In conclusion, making decisions is a crucial component of programming. TypeScript offers a variety of control structures to help you incorporate reasoning. A block of code is executed depending on a condition using the if-else statement. One of the multiple code blocks is chosen using the switch-case statement, and a code block is continually executed using loops.

While a condition is true, a block of code is repeatedly executed in a while loop, a block of code is executed at least once in a do-while loop, and a series of variables are repeatedly iterated over in a for a loop.

Finally, the break statement terminates a loop or switch-case statement before it reaches its natural end.

As a TypeScript developer, it is essential to understand these control structures and use them effectively to write clean, efficient, and maintainable code. Mastering these concepts can make your code more robust and improve quality.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *