TypeScript While Loop
While loop in typescript helps to execute a set of statements enclosed in the loop repeatedly based on a condition.
Unlike TypeScript for loop, while loop does not care about the initialization and update of looping variable. The developer has to take explicit care about the looping variable and the condition that breaks the while loop.
Left unchecked, the while loop can lead to an infinite loop. So, care has to be taken to avoid the program control being in while loop forever.
Syntax
Following is the syntax of TypeScript while loop:
while(condition) {
// set of statements
}
- while is the keyword
- The condition is evaluated and if the result is true, the set of statements are executed. The condition is checked again, and the loop repeats. Whenever the condition evaluates to false, the while loop is broken.
Example 1 – Simple While Loop
Following is a simple while loop iterating for N times.
example.ts
var N = 4
var i = 0
while(i<N){
// set of statement in while loop
console.log(i)
i++ // updating control variable
}
Output
0
1
2
3
Example 2 – Using While Loop for finding factorial
Following example demonstrates the usage of while loop in finding a factorial of a number.
example.ts
var N = 6
var i = 1
var factorial = 1
while(i<=N){
factorial = factorial * i
i++ // updating control variable
}
console.log("factorial of "+N+" is : "+factorial)
Output
factorial of 6 is : 720
Conclusion
In this TypeScript Tutorial, we have learnt the syntax and usage of while loop with example programs. In our next tutorial, we shall learn about do while loop.