TypeScript for Loop

TypeScript for loop is used to execute a block of statements repeatedly when a condition is satisfied. During the repetition, the state of program changes which effects the looping condition, and when the looping condition is not satisfied, the loop stops and continues with the rest of the following statements in the program.

Syntax – TypeScript for loop

Following is the syntax of for loop in typescript :

</>
Copy
 for (looping_variable; condition; update_looping_variable) {
     // block of statements
 }

looping_variable is used as a means to effect condition which in-turn effects the execution of the block of statements in for loop repeatedly. update_looping_variable is the place where looping_variable could be modified for each repetition.

Typical Example of TypeScript for loop

Following is a typical example of for loop, where a counter is initialized, and incremented by 1 each time the loop is executed and the condition is such that the counter does not exceed a limit value.

example.ts

</>
Copy
for(var counter:number = 1; counter<10; counter++){
    console.log("for loop executed : " + counter)
}

Output

for loop executed : 1
for loop executed : 2
for loop executed : 3
for loop executed : 4
for loop executed : 5
for loop executed : 6
for loop executed : 7
for loop executed : 8
for loop executed : 9

for-in loop

To iterate over a set of values such as arraytuple, etc., TypeScript provides for-in loop to iterate a set of statement for each element in the data set. Note that only the index of element is accessible inside the loop, not the actual item of dataset. To get the item value in dataset, use the index and the dataset, like arr[item].

Syntax

Following is the syntax to use for-in loop.

</>
Copy
 for (var item in dataset) { 
     // block of statements 
 }

Example for-in loop with array

A working example is provided below where for-in loop is applied on an array of numbers :

example.ts

</>
Copy
var arr:number[] = [10, 65, 73, 26, 44]

for(var item in arr){
    console.log(arr[item])
}

Output

10
65
73
26
44

Upon compiling to JavaScript, tsc generates following .js code.

example.js

</>
Copy
var arr = [10, 65, 73, 26, 44];
for (var item in arr) {
    console.log(arr[item]);
}

Example for-in loop with tuple

A working example is provided below where for-in loop is applied on tuple.

example.ts

</>
Copy
var student = [10, "John", "Spanish"]

for(var item in student){
    console.log(student[item])
}

Output

10
John
Spanish

Upon compiling to JavaScript, tsc generates following .js code.

example.js

</>
Copy
var student = [10, "John", "Spanish"];
for (var item in student) {
    console.log(student[item]);
}

Conclusion

In this TypeScript Tutorial, we have learnt how to execute a block of statement repeatedly using a for loop with example programs. Also we learnt how to use for loop to repeat a set of statements for each element in data sets like array, tuple, etc.