TypeScript for..of Loop Example

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

for..of loop Examples

In TypeScript, you can iterate over iterable objects (including array, map, set, string, arguments object and so on) using for...of loop.
// Example of using 'for...of' to iterate over array elements.
let array = [10, 20, 30, 40];
for (let val of array) {
    console.log(val); // prints values: 10, 20, 30, 40
}

//Example of using 'for...of' to iterate over a string.
let str = "Java Guides";

for (let char of str) {
  console.log(char); 
}
Output:
C:\typescript-tutorial> tsc for-loops.ts
C:\typescript-tutorial> node for-loops.js
10
20
30
40
J
a
v
a

G
u
i
d
e
s
Loop over an array of strings using for..of loop:
// Using “for…of” loop
let programmingLangs : string[] = ['C', 'C++', 'Java', 'JavaScript'];
for(let element of programmingLangs){
    console.log(element);
}

Reference



Comments