Control Structures in TypeScript (Live Playground)
Control structures in TypeScript allow you to control the flow of your code.
In this tutorial, we will explore control structures in TypeScript. Understanding how to use various control structures will enable you to write clean, efficient, and effective TypeScript code.
If-else Statements
If-else statements are used to conditionally execute blocks of code:
TypeScript
let age = 18;
if (age >= 18) {
console.log('You are an adult.');
} else {
console.log('You are not an adult.');
}
Live Playground, Try it Yourself
Switch Statements
Switch statements are used to perform different actions based on different conditions:
TypeScript
let day = 3;
switch (day) {
case 0:
console.log('Sunday');
break;
case 1:
console.log('Monday');
break;
case 2:
console.log('Tuesday');
break;
case 3:
console.log('Wednesday');
break;
case 4:
console.log('Thursday');
break;
case 5:
console.log('Friday');
break;
case 6:
console.log('Saturday');
break;
default:
console.log('Invalid day');
}
Live Playground, Try it Yourself
Loops
Loops are used to repeatedly execute a block of code:
TypeScript
// for loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// while loop
let j = 0;
while (j < 5) {
console.log(j);
j++;
}
// do-while loop
let k = 0;
do {
console.log(k);
k++;
} while (k < 5);
Live Playground, Try it Yourself
Conclusion
In this tutorial, we have explored control structures in TypeScript. Understanding how to use various control structures effectively will enable you to write clean, efficient, and functional TypeScript code.