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:
The loop continues executing the code block as long as the specified condition remains true.
Using break for early exit
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
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
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:
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.