In TypeScript, we can iterate through iterable objects (including array, map, set, string, arguments object
and so on) using various for
loops.
TypeScript supports 3 kind of for
loops:
for
loop (traditional for-loop)for..of
loopfor..in
loop
1. TypeScript for-loop
Examples
1.1. Traditional for
loop
for (first expression; second expression; third expression) { // statements inside loop will be executed for each iteration }
Traditional for
loop is used to execute a block of code until a specified condition (second expression) is true
. After each iteration, a statement (third expression) is executed which can be used to increment or decrement the counter used in the second expression.
for (let counter = 0; counter < 5; counter++) { console.log ("Value of counter: " + i); }
1.2. for..of
loop
for (let val of iterable) { //Statements }
This loop helps in iterating over iterable objects such as list
, set
, map
or string
. With the help of this loop, we do not need to manage a counter variable explicitly.
let myArray = [10, 20, 30]; for (let value of myArray) { console.log(value); //10 20 30 }
let str = "Hello World"; for (var ch of str) { console.log(ch); //H e l l o W o r l d }
1.3. for..in
loop
for (let val in collection) { //Statements }
This loop helps in iterating the indexed collections such as an array
, list
, or tuple
. While iterating over the values, it returns an index on each iteration.
let myArray = [10, 20, 30]; for (let index in myArray) { console.log(index); //Prints indexes console.log(arr[index]); //Prints values }
2. More Examples
2.1. Iterating through an Array
Example of using for
loop to iterate over array
elements.
let myArray = [10, 20, 30]; for (let value of myArray) { console.log(value); //10 20 30 }
2.2. Iterating through a Map
Example of using 'for...of'
to iterate over map
entries.
let map = new Map(); map.set("A",1); map.set("B",2); map.set("C",3); //Iterate over map keys for (let key of map.keys()) { console.log(key); //A B C } //Iterate over map values for (let value of map.values()) { console.log(value); //1 2 3 } //Iterate over map entries for (let entry of map.entries()) { console.log(entry[0], entry[1]); //"A" 1 "B" 2 "C" 3 } //Using object destructuring for (let [key, value] of map) { console.log(key, value); //"A" 1 "B" 2 "C" 3 }
2.3. Iterating through a Set
Example of using 'for...of'
to iterate over set
entries.
let mySet = new Set(); mySet.add('A'); mySet.add('B'); mySet.add('C'); //Iterate over set for (let entry of mySet) { console.log(entry); //A B C }
2.4. Iterating through a String
Example of using 'for...of'
to iterate over string
. During iteration, you will get one single character from string
in each loop cycle.
let blogName:string = "howtodoinjava.com"; //Iterate over set for (let character of blogName) { console.log(character); //howtodoinjava.com }
Drop me your questions in the comments section.
Happy Learning !!