TypeScript For-loop, For..of and For..in

In TypeScript, we can use the for-loops to iterate through the iterable objects such as array, map, set, string, arguments object and so on. This article explores the TypeScript for-loop, and its syntax, providing code examples, and explaining its various components.

TypeScript supports 3 types of for-loops:

  • Traditional for loop: To get precise control over iterations.
  • for..of loop: To iterate over iterable objects such as an array, set, map, or values.
  • for..in loop: To iterate over object properties
const array = [1, 2, 3, 4, 5];

//Traditional For Loop
for (let i = 0; i < array.length; i++) {
  const element = array[i];
  // Code to execute with 'element' in each iteration
}

//For..of Loop
for (const element of array) {
  // Code to execute with 'element' in each iteration
}

//For..in Loop
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
};

for (const key in person) {
  const value = person[key];
  // Code to execute with 'key' and 'value' in each iteration
}

1. Exploring For-Loops in TypeScript

1.1. The Traditional ‘for‘ Loop

The traditional for loop is the most familiar looping construct that is available in most programming languages. It’s characterized by its initialization, condition, and increment (or decrement) parts.

for (initialization; condition; increment/decrement) {
    // Code to execute in each iteration
}

Traditional for loop executes a block of code until a specified condition is true. After each iteration, a statement (increment/decrement) is executed, which increments or decrements the counter used in the condition.

for (let i = 0; i < 5; i++) {
    console.log(i);   //Outputs 0 1 2 3 4
}

1.2. The ‘for..of‘ Loop

Introduced in ECMAScript 2015 (ES6), the for..of loop simplifies iterating over iterable objects like arrays, strings, maps, and sets. With the help of ‘for..of‘ loop, we do not need to manage a counter variable explicitly.

for (variable of iterable) {
    // Code to execute in each iteration
}

In the following example, the for..of loop iterates over each element of the colors array, allowing direct access to the values without managing indices.

const colors = ["red", "green", "blue"];
for (const color of colors) {
    console.log(color);
}

1.3. The ‘for..in‘ Loop

The for..in loop is used to iterate over the properties of an object. It’s generally not recommended for iterating over arrays due to potential issues described later in this article.

for (property in object) {
    // Code to execute in each iteration
}

In the following example, we are iterating over the properties of the person object.

const person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
};

for (const key in person) {
    console.log(key, person[key]);
}

The program output:

[LOG]: "firstName",  "John" 
[LOG]: "lastName",  "Doe" 
[LOG]: "age",  30 

2. For Loop Examples

Let us see a few examples of iterating over different types of collections and objects in TypeScript.

2.1. Using ‘for..of‘ Loop to Iterate through an Array

Example of using ‘for..of‘ loop to iterate over elements of the array.

let myArray = [10, 20, 30]; 

for (let value of myArray) {
  console.log(value); 	//10 20 30
}

2.2. Using ‘for..of‘ Loop to Iterate through Map Entries

Example of using 'for...of' to iterate over Map entries.

const map = new Map<string, number>();
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. Using ‘for..of‘ Loop to Iterate through a Set

Example of using 'for...of' to iterate over Set elements.

let mySet = new Set<string>();
mySet.add('A');
mySet.add('B');
mySet.add('C');
 
for (let entry of mySet) {
    console.log(entry);   //A B C
}

2.4. Using ‘for..of‘ to Iterate through a String

Example of using 'for...of' to iterate over string. During iteration, we will get one single character from string in each loop cycle.

let blogName:string = "typescript";
 
//Iterate over set 
for (let character of blogName) {
    console.log(character);   //t y p e s c r i p t
}

3. Do not use ‘for..in‘ loop to iterate through an array

The for..in loop in JavaScript and TypeScript is designed to iterate over the properties of an object. While it might seem tempting to use it for arrays, there are potential issues that can arise.

For example, consider the following example of colors array. When we iterate over its elements, everything seems normal.

const colors = ["red", "green", "blue"];

for (const index in colors) {
    console.log(index, colors[index]);
}

The program output:

[LOG]: "0",  "red" 
[LOG]: "1",  "green" 
[LOG]: "2",  "blue"

The output seems correct. However, let’s see what happens when we introduce an additional property to the array’s prototype:

Array.prototype.extraProperty = "unexpected";

for (const index in colors) {
    console.log(index, colors[index]);
}

The program output:

0 red
1 green
2 blue
extraProperty unexpected

Notice the above output. It prints the additional property added to the Array.prototype object also because the for..in loop iterates over all enumerable properties of an object, including those inherited from its prototype chain.

In real-life applications, this behavior can lead to unintended consequences when working with arrays.

4. Conclusion

The following table summarizes the important points related to all 3 variants of for-loop in TypeScript.

FeatureTraditional for Loopfor..of Loopfor..in Loop
When to usePrecise control over iterationsIterate over iterable objectsIterate over object properties
Syntaxfor (initialization; condition; increment/decrement){ … }for (variable of iterable){ … }for (property in object){ … }
Iterates overIndices (often used with arrays)Collections and Values (elements)Properties of an object
Access to IndexYesNoNo
Prototype PropertiesNot an issueNot an issueCan include unexpected properties
PerformanceGenerally performs wellGenerally performs wellPotentially slower
Break StatementYesYesYes
Continue StatementYesYesYes

Drop me your questions in the comments section.

Happy Learning !!

Comments

Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode