TypeScript While loop

Loops are fundamental constructs in programming that enable the execution of a block of code multiple times based on a condition. In TypeScript, loops help automate repetitive tasks, manage iterations over data structures, and control the flow of the program efficiently. The primary types of loops in TypeScript include for, while, and do...while loops.

What is while Loop in TypeScript?

The while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop continues to execute as long as the specified condition evaluates to true. Once the condition becomes false, the loop terminates, and the program proceeds to the next statement following the loop.

Syntax of the while Loop

The syntax of the while loop in TypeScript is straightforward:

tsx
1
2
3
while (condition) {
    // Code to be executed
}
  • condition: A Boolean expression evaluated before each iteration. If it returns true, the loop's body executes; if false, the loop terminates.

Practical Examples of the while Loop

Example 1: Counting from 1 to 5

tsx
1
2
3
4
5
6
let count: number = 1;

while (count <= 5) {
    console.log(`Count is: ${count}`);
    count++;
}

Explanation:

  • A variable count is initialized to 1.
  • The while loop checks if count is less than or equal to 5.
  • If the condition is true, it prints the current value of count and then increments count by 1.
  • The loop continues until count exceeds 5.

Output:

batchfile
1
2
3
4
5
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

Example 2: Summing Numbers Until a Threshold

tsx
1
2
3
4
5
6
7
8
let sum: number = 0;
let num: number = 1;

while (sum < 10) {
    sum += num;
    console.log(`Added ${num}, total sum is: ${sum}`);
    num++;
}

Explanation:

  • Variables sum and num are initialized to 0 and 1, respectively.
  • The loop adds num to sum and prints the operation.
  • num is then incremented by 1.
  • The loop continues until sum is no longer less than 10.

Output:

batchfile
1
2
3
4
Added 1, total sum is: 1
Added 2, total sum is: 3
Added 3, total sum is: 6
Added 4, total sum is: 10

Common Pitfalls and How to Avoid Them

  • Infinite Loops: An infinite loop occurs when the loop's condition always evaluates to true. This can cause the program to become unresponsive. To prevent this, ensure that the condition will eventually become false, typically by modifying a variable within the loop.
  • Example of an Infinite Loop:
tsx
1
2
3
4
5
6
let i: number = 0;

while (i < 5) {
    console.log(i);
    // Missing increment of i
}

Solution:

tsx
1
2
3
4
5
6
let i: number = 0;

while (i < 5) {
    console.log(i);
    i++; // Incrementing i to eventually terminate the loop
}
  • Off-by-One Errors: These errors occur when the loop iterates one time too many or one time too few. Carefully consider the loop's condition and the initial value of the variables involved.
  • Example of an Off-by-One Error:
tsx
1
2
3
4
5
6
let i: number = 1;

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

Output:

batchfile
1
2
3
4
5
1
2
3
4
5
  • If the condition were i < 5, the loop would miss printing 5.

The do...while Loop

The do...while loop is similar to the while loop, with one key difference: the condition is evaluated after the loop's body has executed. This guarantees that the loop's body runs at least once, regardless of whether the condition is true or false initially.

Syntax of the do...while Loop

The syntax for the do...while loop is as follows:

tsx
1
2
3
do {
    // Code to be executed
} while (condition);
  • condition: A Boolean expression evaluated after each iteration. The loop continues as long as it returns true.

Practical Examples of the do...while Loop

The do...while loop in TypeScript makes it particularly useful in scenarios where an initial action is required, and subsequent iterations depend on a condition.

  • Example 1: Consider a scenario where we want to display a message to the user at least once, regardless of a condition.
tsx
1
2
3
4
5
6
let i: number = 5;

do {
    console.log(`Value of i is: ${i}`);
    i++;
} while (i < 5);

Explanation:

  • Initialization: The variable i is initialized to 5.
  • do Block: The code inside the do block executes, printing the current value of i (5) to the console.
  • Increment: The variable i is incremented by 1, making it 6.
  • Condition Check: The condition i < 5 is evaluated. Since 6 is not less than 5, the condition is false, and the loop terminates.

Output:

batchfile
1
Value of i is: 5

Comparing while and do...while Loops

Both while and do...while loops are used for repeating code blocks based on a condition, but they differ in when the condition is evaluated:

  • while Loop: Evaluates the condition before executing the loop's body. If the condition is false initially, the loop's body may not execute at all.
  • Example:
tsx
1
2
3
4
5
6
let count: number = 5;

while (count < 5) {
    console.log(`Count is: ${count}`);
    count++;
}

Output: (No output, as the condition is false initially.)

  • do...while Loop: Executes the loop's body once before evaluating the condition. This ensures that the loop's body runs at least once, regardless of the condition.
  • Example:
tsx
1
2
3
4
5
6
let count: number = 5;

do {
    console.log(`Count is: ${count}`);
    count++;
} while (count < 5);

Output:

batchfile
1
Count is: 5

Use Cases for while and do...while Loops

  • while Loop: Ideal when the number of iterations is not predetermined, and it's possible that the loop may not execute at all if the condition is false initially.
  • Example: Reading User Input Until Valid
tsx
1
2
3
4
5
let userInput: string | null = null;

while (userInput === null || userInput.trim() === "") {
    userInput = prompt("Enter a valid name:");
}
  • do...while Loop: Suitable when the loop's body must execute at least once, such as when prompting a user for input and validating it after the first entry.
  • Example: Menu Selection
tsx
1
2
3
4
5
6
7
8
let selection: number;

do {
    console.log("1. Option One");
    console.log("2. Option Two");
    console.log("3. Exit");
    selection = parseInt(prompt("Enter your choice:") || "0", 10);
} while (selection !== 3);

Best Practices for Using Loops in TypeScript

  • Ensure Termination: Always guarantee that the loop's condition will eventually become false to prevent infinite loops.
  • Example:
tsx
1
2
3
4
5
6
let i: number = 0;

while (i < 10) {
    console.log(i);
    i++; // Increment to ensure termination
}
  • Avoid Side Effects: Be cautious of modifying variables outside the loop that are part of the loop's condition, as this can lead to unexpected behavior.
  • Example to Avoid:
tsx
1
2
3
4
5
6
let i: number = 0;

while (i < 5) {
    console.log(i);
    // Avoid modifying 'i' outside the loop's control
}
  • Use Appropriate Loop Types: Choose the loop type (for, while, do...while) that best fits the scenario for clarity and maintainability.
  • Example:
tsx
1
2
3
4
5
6
7
8
9
10
11
// Using 'for' loop for a known number of iterations
for (let i = 0; i < 5; i++) {
    console.log(i);
}

// Using 'while' loop when iterations depend on a condition
let count: number = 0;
while (someCondition) {
    // Code
    count++;
}

Frequently Asked Questions