Typescript for Loop Example

This post shows how to use for loop in TypeScript with an example.

Read more at https://www.javaguides.net/2019/10/typescript-for-loop-forof-loop-for-in.html.

for loop Examples

The for loop is used to execute a block of code a given number of times, which is specified by a condition.

Syntax:

for (first expression; second expression; third expression ) {
    // statements to be executed repeatedly
}

Simple for Loop Example

Let's create a file "for-loops.ts" and add the following code to it:
for(let i = 0; i < 5; i++){
    console.log("element " + i);
}

// Loop over an Array Using for Loop
typescript
let array = [10, 20, 30, 40];
for (let index = 0; index < array.length; index++) {
    const element = array[index];
    console.log(element);
}
Output:
C:\typescript-tutorial> tsc for-loops.ts
C:\typescript-tutorial> node for-loops.js
element 0
element 1
element 2
element 3
element 4
10
20
30
40
Loop over strings using for loop:
// Using traditional for loop 
let programmingLangs : string[] = ['C', 'C++', 'Java', 'JavaScript'];
for (var i = 0; i < programmingLangs.length; i++) {
    console.log(programmingLangs[i]);    
}

References



Comments