Mastering Loops in TypeScript: A Comprehensive Guide
Unlocking the Power of while Loops
In TypeScript, the while loop is a fundamental control structure that allows you to execute a block of code repeatedly as long as a specified condition remains true. The syntax is straightforward: while (condition) { code to execute }. Here’s how it works:
- The condition is evaluated first. If it’s true, the code inside the curly braces is executed.
- The condition is evaluated again, and if it’s still true, the code is executed again.
- This process continues until the condition becomes false, at which point the loop terminates.
Example 1: Counting from 1 to 3
Let’s see this in action with a simple example that displays numbers from 1 to 3:
let i = 1;
while (i <= 3) {
console.log(i);
i++;
}
Harnessing the Power of do…while Loops
The do…while loop is similar to the while loop, but with a key difference: it executes the code block at least once before evaluating the condition. The syntax is: do { code to execute } while (condition). Here’s how it works:
- The code inside the curly braces is executed first.
- Then, the condition is evaluated. If it’s true, the code is executed again.
- This process continues until the condition becomes false, at which point the loop terminates.
Example 3: Counting Down from 3 to 1
Let’s see this in action with an example that displays numbers from 3 to 1:
let i = 3;
do {
console.log(i);
i--;
} while (i >= 1);
Key Differences between while and do…while Loops
So, what’s the main difference between these two loop types? Simply put, a do…while loop executes its body at least once, whereas a while loop may not execute its body at all if the condition is false from the start.
Example 4: Summing Positive Numbers
Let’s see this in action with an example that sums only positive numbers:
let sum = 0;
do {
let num = Number(prompt("Enter a number: "));
if (num > 0) {
sum += num;
} else {
break;
}
} while (true);
console.log("Sum of positive numbers: ", sum);
Avoiding Infinite Loops
Be careful when working with loops, as infinite loops can cause your program to crash. An infinite loop occurs when the condition is always true, causing the loop body to run forever. For example:
let i = 0;
while (i < 5) {
console.log(i);
// missing increment statement!
}
Choosing the Right Loop for the Job
When deciding between a for loop, while loop, and do…while loop, ask yourself:
- Do I know the exact number of iterations required? Use a for loop.
- Does the termination condition vary? Use a while loop.
- Do I need to execute the code block at least once? Use a do…while loop.
By mastering these loop types, you’ll be well on your way to writing efficient, effective, and error-free TypeScript code.