Loops in TypeScript

Loops are used to execute certain set of statements n number of times.

There are three types of loops in TypeScript: for loop, while loop and do-while loop.

for loop

for loop is used when we know the number of times we want to execute a set of statements.
Below is a sample code:

var i:number;
for(i=1; i<=10; i++){
    console.log(i);
}

Below is the output of above code:

while loop

while loop is used when we are not sure how many number of times we want to execute a set of statements.
Below is a sample code:

var num:number=30;
while(num>0 && num%3==0){
    console.log(num/3);
    num-=3;
}

Below is the output of above code:

do-while loop

do-while loop is just like while loop. The only difference is if the condition is false, while loop will not be executed even once, do-while will be executed at least once.
Below is a sample code:

var num:number=30;
do{
    console.log("Do-While loop will be executed at least once even if the condition is false!");
}while(num>40)

Below is the output of above code:

Design a site like this with WordPress.com
Get started