For Loop in TypeScript

In TypeScript, the for loop is a powerful construct that allows you to iterate over arrays or other iterable objects to perform a certain operation. It is a fundamental tool in programming, and knowing how to use it effectively can make your code more concise and efficient. In this lesson, we will go over the syntax of for loops in TypeScript and explore some examples of how to use them.

The basic syntax for a for loop in TypeScript is as follows:

for (let i = 0; i < arr.length; i++) {
  // code to execute for each element in the array
}

The loop starts with the for keyword, followed by parentheses containing three parts: the initialization, the condition, and the incrementation. In the example above, the initialization sets the variable i to 0, the condition checks if i is less than the length of the array arr, and the incrementation increases i by 1 after each iteration. The code inside the curly braces is executed for each element in the array.

Let’s look at some examples of how to use for loops in TypeScript.

Example 1: Iterating over an array

const nums = [1, 2, 3, 4, 5];

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

This code iterates over the nums array and logs each element to the console.

Example 2: Iterating over an object

const obj = {
  name: "Alice",
  age: 30,
  city: "New York",
};

for (const key in obj) {
  console.log(`${key}: ${obj[key]}`);
}

This code iterates over the obj object and logs each key-value pair to the console.

Example 3: Nested for loops

const rows = 5;
const cols = 5;

for (let i = 0; i < rows; i++) {
  for (let j = 0; j < cols; j++) {
    console.log(`(${i}, ${j})`);
  }
}

This code uses nested for loops to iterate over a 2D grid and log each coordinate to the console.

In conclusion, the for loop is a versatile and powerful construct in TypeScript that can be used to iterate over arrays, objects, or any other iterable data structure. By understanding the syntax and best practices for using for loops, you can make your code more concise and efficient.