How to Use the For Loop in TypeScript?

As a TypeScript developer, you should know how to work with for loop in TypeScript. In this tutorial, I will explain how to use the for loop in TypeScript with detailed examples, including syntax.

What is a For Loop in TypeScript?

A for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It is commonly used for iterating over arrays or collections. In TypeScript, the for loop is similar to JavaScript but with added type safety features.

Syntax of a For Loop in TypeScript

The syntax of a for loop in TypeScript is:

for (initialization; condition; increment) {
    // code to be executed
}
  • Initialization: Initializes one or more loop counters.
  • Condition: Evaluated before each loop iteration. If true, the loop continues; if false, the loop ends.
  • Increment: Updates the loop counter after each iteration.

Read Functions in TypeScript Interfaces

TypeScript For Loop Examples

Now, let me show you some examples of using for loop in TypeScript.

1. Iterate Over an Array of Cities

Let’s start with a simple example of iterating over an array of cities in TypeScript with for loop.

let cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];

for (let i = 0; i < cities.length; i++) {
    console.log(cities[i]);
}

In this example:

  • We initialize i to 0.
  • The condition i < cities.length ensures the loop runs as long as i is less than the length of the array.
  • The increment i++ increases i by 1 after each iteration.

Here is the exact output in the screenshot below:

TypeScript For Loop

Read for…in Loops in TypeScript

2. Sum Up an Array of Numbers

Here is another for loop example in TypeScript.

Consider an array of population counts from different states:

let populations: number[] = [8175133, 3792621, 2695598, 2328000, 1680992];
let totalPopulation: number = 0;

for (let i = 0; i < populations.length; i++) {
    totalPopulation += populations[i];
}

console.log("Total Population:", totalPopulation);

Here, the for loop iterates through the populations array, summing up the values to calculate the total population.

Read Exclamation Mark in TypeScript

3. Using a For Loop with Objects

Let me show you another example.

You can also use for loops to iterate over properties of an object. Suppose we have an object representing the population of various cities:

interface CityPopulation {
    [city: string]: number;
}

let cityPopulations: CityPopulation = {
    "New York": 8175133,
    "Los Angeles": 3792621,
    "Chicago": 2695598,
    "Houston": 2328000,
    "Phoenix": 1680992
};

for (let city in cityPopulations) {
    console.log(`${city}: ${cityPopulations[city]}`);
}

In this example, the for loop iterates over the keys of the cityPopulations object, logging each city and its population.

Here is the exact output in the screenshot below:

For Loop in TypeScript

Check out Continue Statement in TypeScript For Loops

4. Nested For Loops in TypeScript

Nested for loops are useful for working with multidimensional arrays. Here’s an example of a 2D array representing a grid of temperatures, and the complete TypeScript code is below.

let temperatures: number[][] = [
    [73, 75, 79, 80],
    [68, 70, 72, 74],
    [65, 67, 69, 71]
];

for (let i = 0; i < temperatures.length; i++) {
    for (let j = 0; j < temperatures[i].length; j++) {
        console.log(`Temperature at [${i}, ${j}]: ${temperatures[i][j]}°F`);
    }
}

This nested for loop iterates through each row and column of the temperatures array, logging the temperature at each position.

TypeScript For Loops with Index

Here, I will show you how to use TypeScript for loops with an index variable to keep track of the current iteration.

The for loop in TypeScript allows you to easily include an index variable that increments each iteration. Here’s an example:

const cities = ['New York', 'Los Angeles', 'Chicago', 'Houston'];

for (let i = 0; i < cities.length; i++) {
  console.log(`Index ${i}: ${cities[i]}`);
}

This will output:

Index 0: New York
Index 1: Los Angeles 
Index 2: Chicago
Index 3: Houston

The i variable starts at 0 and increments by 1 each loop iteration until it reaches the length of the cities array. We can use i inside the loop to access the index and value at that position.

Here is the exact output in the screenshot below:

TypeScript For Loops with Index

Conclusion

The for loop in TypeScript is used to iterate over arrays, objects, and more. In this tutorial, I explained how to work with TypeScript for loops, its syntax, and also some examples.

You may also like: