Skip to main content

While Loop

In Typescript, as in many other programming languages, we often encounter situations where we need to repeatedly execute a block of code until a certain condition is met. This is where loops come into play. One of the most basic looping structures is the 'While Loop'. In this tutorial, we will explore the while loop in depth, its syntax, usage, and some common pitfalls to avoid.

The While Loop - Syntax

The syntax of the while loop in TypeScript is very straightforward:

while (condition) {
// code to be executed
}

The 'condition' in the while loop is a boolean expression. The code inside the loop will keep on executing as long as the condition remains true. Once the condition is false, the loop will terminate, and the control will move to the next line of code after the loop.

Here is a simple example:

let i = 0;

while (i < 5) {
console.log(i);
i++;
}

In this example, the loop will print the values from 0 to 4. Initially, 'i' is 0, and the condition i < 5 is true, so the loop begins. After each iteration, 'i' is incremented by 1. When 'i' becomes 5, the condition i < 5 becomes false, and the loop terminates.

Infinite While Loops

One common pitfall when working with while loops is the infinite loop. This happens when the loop's condition never becomes false. For example:

let i = 0;

while (i < 5) {
console.log(i);
// forgot to increment i
}

In this case, the loop will never terminate because 'i' is always less than 5. This will lead to your program becoming unresponsive. Therefore, always ensure that the loop's condition will eventually become false.

Break and Continue Statements

You can control the flow of the while loop using break and continue statements.

  • break statement: It is used to exit the loop prematurely. It is useful when you have found what you were looking for and do not need to complete the remaining iterations.
let i = 0;

while (i < 5) {
if (i === 3) {
break;
}
console.log(i);
i++;
}

In this example, the loop will terminate when 'i' becomes 3, even though the loop's condition i < 5 is still true.

  • continue statement: It is used to skip the current iteration and move to the next one immediately.
let i = 0;

while (i < 5) {
i++;
if (i === 3) {
continue;
}
console.log(i);
}

In this example, the number 3 will not be printed because when 'i' is 3, the continue statement causes the loop to skip to the next iteration immediately.

To summarize, the while loop is a powerful tool in TypeScript that can simplify your code by performing repetitive tasks efficiently. However, be careful when defining the loop's condition to avoid infinite loops, and use break and continue statements to control the flow of the loop when needed. Happy coding!