Typescript - Learn while loop examples
- Admin
- Feb 24, 2024
- Typescript
In this tutorial, we’ll explore while loops in TypeScript through examples. TypeScript provides two versions of while loops:
- How to write a while loop in TypeScript?
- How to use a do-while loop in TypeScript?
While Loop in TypeScript
Like every programming language, TypeScript offers a while loop. A while loop executes the statements within its code block as long as the conditional expression evaluates to true. If the expression is false, the code block is skipped.
while
is a reserved keyword in TypeScript. This loop is commonly used for iterating over collections such as objects, arrays, sets, and maps.
Syntax:
while (conditionalExpression) {
// Code block statements
}
Finite Example of a while Loop
This example iterates the loop 5 times and outputs a counter to the console log.
let counter = 1;
while (counter <= 5) {
console.log(counter);
counter++;
}
Output:
1
2
3
4
5
How to Use the Break Keyword in a While Loop with an Example?
The break
keyword allows you to exit from the execution of a while loop. It is used when a certain conditional expression is true.
Syntax:
break;
Here’s an example:
let counter = 1;
while (counter <= 6) {
if (counter % 3 == 0) {
console.log("IF Condition met");
break; // The while loop exits here when the first number divisible by 3 is encountered
}
counter++;
}
Output:
IF Condition met
while loop Infinite Example
An infinite
loop occurs when the conditional expression is always true.
while (true) {
console.log("Infinite loop");
}
Output:
Infinite loop
Infinite loop
Infinite loop
How to Use Async and Await in a While Loop?
async
and await
are used for handling asynchronous operations. Here’s an example.
const getRecords = async (_) => {
let isFlag = false;
while (!isFlag) {
let res = await fetch("/api/get");
if (res.status === 200) isFlag = true;
}
};
By marking getRecords
as async, we can use await
within the loop to pause execution until a promise is fulfilled.
While loop works same with these async and await .
Conclusion
In conclusion, we’ve covered while looping in TypeScript with examples, including both finite and infinite scenarios, the usage of the break
keyword, and examples involving async
and await
.