While loop in TypeScript

In contrast to the predictable steps of for loops, TypeScript's while loop excel at iterating as long as a specific condition remains true. They dance to the rhythm of logic, repeating their steps till the music stops.

Basic while loop

The basic structure of a while loop is as follows:

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

The loop continues executing the code block as long as the specified condition remains true.

Using break for early exit

let password = ""; while (password.length < 8) { password = prompt("Enter your password: "); if (password.length >= 8) { break; // Exits the loop when password meets minimum length } console.log("Password needs to be at least 8 characters."); } if (password.length === 8) { console.log("Password accepted."); } else { console.log("Please try again with a longer password."); }

This loop prompts the user for a password repeatedly until it meets the minimum length. The break statement within the if block allows early exit once the condition is fulfilled. This demonstrates controlled iteration based on user input.

Looping with external data

const data = [1, 3, 5, 7, 9]; let index = 0; while (index < data.length) { console.log(data[index]); index++; }

This loop iterates through an array of numbers. It uses the index variable to access each element and print it. This exemplifies how while loops can handle various data sources with appropriate conditions.

Combining with other control flow statements

let sum = 0; let number = 1; while (number <= 100) { if (number % 2 === 0) { sum += number; // Skip odd numbers } number++; } console.log("Sum of even numbers from 1 to 100:", sum);

This loop demonstrates while combined with an if statement for selective iteration. It adds only even numbers from 1 to 100, showcasing flexible control within the loop flow.

Infinite while loop with a break statement

You can create an infinite loop and use a break statement to exit the loop when a certain condition is met. For example, this loop prints numbers until it reaches 3:

let j = 0; while (true) { console.log(j); if (j === 3) { break; // exit the loop when j is 3 } j++; }

The break statement terminates the loop when j equals 3.

Conclusion

The while loops are useful when the number of iterations is not known beforehand, and the loop continues until a specific condition is met. It's crucial to ensure that the loop's condition eventually becomes false to prevent infinite loops.