In a programming language, loops are the sequence of instructions which continually repeated until a specific condition is not found. It makes the code compact. We can mostly use it with the array. Below is the general structure of the loop statement:
We can classify the loops into two types:
In Indefinite loops, the number of iterations is not known before beginning the execution of the block of statements. There are two indefinite loops:
The TypeScript while loop iterates the elements for the infinite number of times. It executes the instruction repeatedly until the specified condition evaluates to true. We can use it when the number of iteration is not known. The while loop syntax is given below.
while (condition) { //code to be executed }
The explanation of while loop syntax is:
While loop starts the execution with checking the condition. If the condition evaluates to true, the loop body statement gets executed. Otherwise, the first statement following the loop gets executed. If the condition becomes false, the loops get terminated, which ends the life-cycle of the loops.
let num = 4; let factorial = 1; while(num >=1) { factorial = factorial * num; num--; } console.log("The factorial of the given number is: "+factorial);
The TypeScript do-while loop iterates the elements for the infinite number of times similar to the while loop. But there is one difference from while loop, i.e., it gets executed at least once whether the condition is true or false. It is recommended to use do-while when the number of iteration is not fixed, and you have to execute the loop at least once. The do-while loop syntax is given below.
do{ //code to be executed }while (condition);
The explanation of do-while loop syntax is:
The do-while loop starts executing the statement without checking any condition for the first time. After the execution of the statement and update of the variable value, it starts evaluating the condition. If the condition is true, the next iteration of the loop starts execution. If the condition becomes false, the loops get terminated, which ends the life-cycle of the loops.
let n = 10; do { console.log(n); n++; } while(n<=15);