loop in typescript

In TypeScript, there are several ways to loop through an array or execute a block of code repeatedly. The most commonly used loops are the for loop, while loop and do..while loop.

For loop

The for loop is used when you know exactly how many times you want to loop through the code. You can loop through an array or any other iterable object using for..of loop in TypeScript.

Here's a basic example of a for loop:

index.ts
// iterating over an array of strings
const colors = ["red", "green", "blue"];

for(let i = 0; i < colors.length; i++){
  console.log(colors[i]);
}

// iterating over an iterable object using for..of loop
const names = new Set(["Alice", "Bob", "Charlie"]);

for(let name of names){
  console.log(name);
}
305 chars
14 lines

While loop

The while loop is used when you don't know exactly how many times the loop needs to be executed. The loop will continue to run until the condition returns false.

Here's a basic example of a while loop:

index.ts
let counter = 1;

while(counter <= 10){
  console.log(counter);
  counter++;
}
79 chars
7 lines

Do..while loop

The do..while loop is similar to the while loop, but the loop body is executed at least once, even if the condition is initially false.

Here's a basic example of a do..while loop:

index.ts
let i = 0;

do{
  console.log(i);
  i++;
}while(i < 10);
57 chars
7 lines

In addition to these loops, TypeScript also provides the forEach method for arrays, which allows you to loop over each element of an array and apply a function to it.

gistlibby LogSnag