6.TypeScript Loops

6.TypeScript Loops

AI Reading

Quick summary of this article

Loops in TypeScript let you repeat the same block of code multiple times without rewriting it. Every loop has three main parts: initialization (starting point), condition (when to stop), and increment/decrement (how to move to the next step). TypeScript offers several loop types, each suited for different situations.

  • While loop: Runs as long as the condition is true. Example: var i:number=0; while(i<=10){ console.log(i); i++; }
  • Do-while loop: Runs the code block once before checking the condition, then repeats while the condition is true.
  • For loop: Combines initialization, condition, and increment in one line. Example: for(var i:number=1; i<=10;i++){ console.log(i); }
  • For...in loop: Iterates over keys (indexes) of an array or tuple. The variable type should be string or any.
  • Key difference: for...in gives you the keys (index numbers), while for...of gives you the actual values in the array.

6.TypeScript Loops

Loops are essential part of any programing language. Using loop you can iterate same statement without writing that again and again. Loop have 3 parts.

1. Initialization 2. Condition 3. Increment or decrement

Example :

While Loop Example :

var i:number=0 // initilization
while(i<=10){ // condition
   console.log(i);
   i++; // increment
}

Output :

Do while Loop

var i = 0;
do{
   console.log(i);
   i++;
}while (i <= 10);

For loop Example

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




for...in loop Example :

Apart from for loop, TypeScript also support for in loop. The for… in loop can be used to repeat over a set of values as in the case of an array or a tuple.

The for…in loop is used to iterate through a list or collection of values. But for for in loop the data type should be string or any.

Difference between for in and for of ‘For in’ displays the keys for the array while ‘for of ‘ displays the value list of the array.

Leave a Reply

Your email address will not be published. Required fields are marked *