
In this tutorial, learn while looping in typescript with examples.
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 counter to the console log
let counter=1;
while(counter<=5) {
console.log(counter);
counter++;
}
Output:
1
2
3
4
5
How to use Break keyword in while loop with example?
Break
keyword is used to exit from 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 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;
}
}
getRecords
method added 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.