Loops in TypeScript - For, While, and Do-While Explained


Introduction

Loops are used to execute a block of code repeatedly. In TypeScript, you can use for, while, and do-while loops to control the flow of your program and perform iterative tasks. Let's explore these loop constructs in TypeScript.


For Loop

The for loop is often used when you know the number of iterations in advance. It consists of an initialization, a condition, and an update expression.


Example:

for (let i = 1; i <= 5; i++) {
console.log("Iteration " + i);
}

While Loop

The while loop is used when you need to execute a block of code as long as a condition is true. It tests the condition before each iteration.


Example:

let count = 0;
while (count < 5) {
console.log("Count: " + count);
count++;
}

Do-While Loop

The do-while loop is similar to the while loop but guarantees that the code block is executed at least once before the condition is tested.


Example:

let num = 5;
do {
console.log("Number: " + num);
num--;
} while (num > 0);

Nested Loops

You can nest loops within other loops to create complex iterative structures.


Example:

for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log("Outer Loop: " + i + ", Inner Loop: " + j);
}
}

Break and Continue

You can use the `break` statement to exit a loop prematurely and the `continue` statement to skip the current iteration and move to the next one.


Example:

for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip iteration 3
}
if (i === 4) {
break; // Exit the loop at iteration 4
}
console.log("Iteration " + i);
}

Conclusion

Loops are powerful tools in TypeScript for performing repetitive tasks and iterating over data structures. Whether it's a for loop for known iterations or a while loop for dynamic conditions, understanding loop constructs is essential for building robust and efficient programs. As you continue your TypeScript journey, explore the use of loops in real-world applications to enhance your programming skills.