Loops in TypeScript



In this tutorial, we will learn about different types of loops in TypeScript. We will cover the basics of `for...of`, `while`, and `do...while` loops.


What is a Loop

A loop is a control flow statement that allows code to be executed repeatedly based on a condition.

Loops

TypeScript supports three types of loops: `for...of` loops, `while` loops, and `do...while` loops.

For...Of Loop

A `for...of` loop is used when iterating over elements of an iterable object, such as arrays or strings. The syntax for the for...of loop is:

for (let item of iterable) {
    // Code block to be executed
}

While Loop

A `while` loop is used when the number of iterations is not known beforehand. The syntax for the while loop is:

while (condition) {
    // Code block to be executed
}

Do...While Loop

A `do...while` loop is similar to a `do-while` loop in other languages, where the code block is executed at least once before checking the condition. The syntax for the do...while loop is:

do {
    // Code block to be executed
} while (condition)


Example 1: Printing Numbers from 1 to 5 using For...Of Loop

  1. Use a for...of loop to print numbers from 1 to 5.

TypeScript Program

let numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
    console.log(num);
}

Output

1
2
3
4
5


Example 2: Printing Numbers from 1 to 3 using While Loop

  1. Declare an integer variable i and initialize it to 1.
  2. Use a while loop to print numbers from 1 to 3.

TypeScript Program

let i = 1;
while (i <= 3) {
    console.log(i);
    i++;
}

Output

1
2
3


Example 3: Printing Numbers from 1 to 3 using Do...While Loop

  1. Declare an integer variable i and initialize it to 1.
  2. Use a do...while loop to print numbers from 1 to 3.

TypeScript Program

let i = 1;
do {
    console.log(i);
    i++;
} while (i <= 3);

Output

1
2
3