Control Structures in TypeScript
Control structures in TypeScript allow you to control the flow of your program. They include conditional statements (if-else) and loops (for, while).
If-Else Statements
The if-else
statement is used to execute a block of code based on a condition.
let age: number = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Ternary Operator
The ternary operator is a concise way to write simple if-else
statements.
let age: number = 20;
let message = age >= 18 ? "You are an adult." : "You are a minor.";
console.log(message);
Switch Statement
The switch
statement is used to execute one of many code blocks based on the value of an expression.
let day: number = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Invalid day");
}
Loops
Loops are used to execute a block of code repeatedly. TypeScript supports for
, while
, and do-while
loops.
// For Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While Loop
let count: number = 0;
while (count < 5) {
console.log(count);
count++;
}
// Do-While Loop
let x: number = 0;
do {
console.log(x);
x++;
} while (x < 5);
For-Of Loop
The for-of
loop is used to iterate over arrays and strings.
let fruits: string[] = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
For-In Loop
The for-in
loop is used to iterate over object properties.
let person = { name: "Alice", age: 25 };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
Break and Continue
Use break
to exit a loop and continue
to skip to the next iteration.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit the loop
}
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i);
}
Interactive Code Examples
Try running these examples in your TypeScript environment to see how they work!
// Interactive Example
let numbers: number[] = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
Practice Problems
Test your understanding with these practice problems:
- Write a TypeScript program to print the first 10 even numbers.
- Write a TypeScript program to find the sum of all elements in an array.
- Write a TypeScript program to check if a number is prime.