TypeScript for loops

Kenny DuMez
Kenny DuMez
Graphite software engineer

TypeScript provides several looping constructs to iterate over data structures like arrays, and other objects. This guide explores the various types of for loops available in TypeScript, including standard for loops, for...in loops, for...of loops, and forEach methods.

The standard for loop in TypeScript follows a familiar syntax seen in many programming languages. It consists of three parts: initialization, condition, and increment/decrement.

Terminal
for (let i = 0; i < 10; i++) {
console.log(i)
}
  • Initialization: let i = 0; sets up the loop variable.
  • Condition: i < 10; checks if the loop should continue running.
  • Increment/decrement: i++ modifies the loop variable after each iteration.
Terminal
let numbers: number[] = [1, 2, 3, 4, 5]
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i])
}

Here, numbers.length ensures the loop runs as long as there are elements in the array. The console.log(numbers[i]); prints each element to the console.

The for...in loop iterates over the keys (or properties) of an object. It is particularly useful for traversing an object's properties.

Terminal
let person = { name: 'John', age: 30, city: 'New York' }
for (let key in person) {
console.log(`${key}: ${person[key]}`)
}
  • Key: let key in person sets up the loop to iterate over each key in the person object.
  • Accessing values: person[key] retrieves the value associated with each key.

Note: The for...in loop is not recommended for arrays as it iterates over the index as strings, which can lead to unexpected behavior.

The for...of loop iterates over the values of an iterable object, such as arrays, strings, and more. It provides a more straightforward way to access array elements compared to a standard for loop.

Terminal
let numbers: number[] = [1, 2, 3, 4, 5]
for (let num of numbers) {
console.log(num)
}
  • Value: let num of numbers sets up the loop to iterate over each value in the numbers array.
  • Iteration: The loop directly accesses each element, making the code cleaner and easier to read.

The forEach method is an array method that executes a provided function once for each array element. It is a higher-order function that takes a callback function as its argument.

Terminal
let numbers: number[] = [1, 2, 3, 4, 5]
numbers.forEach((num) => {
console.log(num)
})
  • Callback function: (num) => { console.log(num); } is the function executed for each array element.
  • Iteration: forEach handles the iteration internally, simplifying the code.

The forEach method can also access the index of each element in the array.

Terminal
numbers.forEach((num, index) => {
console.log(`Index: ${index}, Value: ${num}`)
})

TypeScript's type system allows you to leverage the benefits of type safety when working with loops and arrays. Here’s an example of combining different loops to manipulate array data.

Terminal
let fruits: string[] = ['apple', 'banana', 'cherry']
// Using a standard for loop
for (let i = 0; i < fruits.length; i++) {
console.log(`For loop: ${fruits[i]}`)
}
// Using a for...in loop
for (let index in fruits) {
console.log(`For...in loop: ${fruits[index]}`)
}
// Using a for...of loop
for (let fruit of fruits) {
console.log(`For...of loop: ${fruit}`)
}
// Using forEach
fruits.forEach((fruit, index) => {
console.log(`forEach loop: Index ${index}, Fruit ${fruit}`)
})

TypeScript offers multiple ways to loop through data structures, each with its own advantages. Understanding these different loops allows you to choose the most appropriate one for your specific use case:

  • Standard for loop: Best for scenarios where precise control over iteration is needed.
  • For...in loop: Ideal for iterating over object properties.
  • For...of loop: Great for iterating over iterable objects like arrays and strings.
  • forEach method: Perfect for executing a function on each array element, with built-in callback support.

For more information on for loops in TypeScript see the official documentation.

Graphite
Git stacked on GitHub

Stacked pull requests are easier to read, easier to write, and easier to manage.
Teams that stack ship better software, faster.

Or install our CLI.
Product Screenshot 1
Product Screenshot 2