Typescript - Learn while loop examples
- Admin
- Sep 20, 2023
- Typescript
In this tutorial, learn while looping in typescript with examples. Typescript provides two version of while loops in typescript
- How to write While loop in Typescript?
- How to use do while loop in typescript?
While Loop in typescript
As every programming language provides a while loop
.
While loop
executes the statements of the code block for true
conditional expression.
It first evaluates the conditional expressions, and if they are ‘true,’ the Code block is executed.
Otherwise, the code enclosed within the while loop is not executed.
while
is a keyword in typescript.
This Loop is used to iterate over a collection of ‘objects’ or ‘arrays,’ as well as ‘set’ and ‘Map.’
Syntax:
while (Conditional Expression){
//Code block statements
}
while loop Finite example
This 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 the while loop with an example?
The Break
keyword is used to exit from the while loop
execution.
It is used when some conditional expression is true
Syntax:
break;
Here is an example
let counter = 1;
while (counter <= 6) {
if (counter % 3 == 0) {
console.log("IF Condition met");
break; //While loop exit here for the first matched number divided by 3 is zero
}
counter++;
}
Output:
IF Condition met
while loop Infinite Example
An infinite
loop is executed when the Conditional expression is configured with true.
while (true) {
console.log("Infinite loop");
}
Output:
Infinite loop
Infinite loop
Infinite loop
How to use async and await in the while loop?
async
and await
are used for asynchronous operations.
Let’s see an example
const getRecords = async (_) => {
let isFlag = false;
while (!isFlag) {
let res = await fetch("/api/get");
if (res.status === 200) isFlag = true;
}
};
The getRecords
method added the async
keyword.
Calling these methods pauses the execution of await operation until a promise response is fulfilled.
While loop works as same with conditional expression
Conclusion
To sum up, We learned while looping in typescript with an example with infinite and finite use cases and break keywords.
It also includes async
and await
examples.