Sign in
Topics
Generate React UI with Prompts or Figma Import
Looking for a cleaner way to handle loops in TypeScript? The forEach method offers a straightforward approach to iterating over arrays while keeping code concise and readable. In this blog, we’ll walk through how it works, when to use it, and the situations where other looping methods might be a better fit.
Writing code that is clear, readable, and easy to maintain is what every developer aims for. One common challenge is iterating over arrays without making the code look messy.
That’s where foreach TypeScript shines. Instead of juggling traditional loops, you can write shorter and more meaningful logic.
But how does this method work, and why is it better than the usual loop structure?
Let’s break it down step by step and see how you can apply it to simplify your everyday TypeScript projects.
The foreach method is a built-in array method that allows you to perform operations on each element of an array without explicitly writing a for or while loop. It is a useful method for dealing with iterative objects. Instead of handling counters, indexes, or managing loop exits, this method executes a callback function for every current element in the array.
The method signature looks like this:
1array.forEach(callbackFn, thisArg?) 2
this
should refer to inside the callback.To use the typescript foreach loop, the syntax stays consistent with JavaScript:
1const numbers: number[] = [1, 2, 3, 4, 5]; 2 3numbers.forEach((value, index, array) => { 4 console.log(`Index: ${index}, Value: ${value}`); 5}); 6
Here:
This foreach function gives three arguments, and the callback function accepts them in that order.
To understand how a foreach loop works, think of it as a helper that automatically goes through all array elements one by one. The method executes the provided callback on each item until there are no elements left.
Here’s a small diagram:
This shows that the foreach method runs in sequence until the last element present is processed.
Let’s take the following example where we want to display integer values:
1const integers: number[] = [10, 20, 30, 40]; 2 3integers.forEach((num) => { 4 console.log(`Number: ${num}`); 5}); 6
Output:
Number: 10
Number: 20
Number: 30
Number: 40
Here, the callback is executed for each element. The loop works without you needing to handle counters.
Using a foreach loop often feels cleaner compared to for or while loops. The table below summarizes the difference:
Feature | foreach loop | for loop / while loop |
---|---|---|
Syntax simplicity | Very short | Longer and includes counters |
Handles index | Optional | Mandatory |
Automatically ends | Yes | Needs condition manually |
Best for | displaying elements, running quick logic | More control (break/continue) |
The typescript foreach loop has some interesting features:
undefined
. Even if you attempt to return from the callback, the method itself will not provide a new array or aggregated result.You can also perform operations inside a callback. For example:
1const numbers: number[] = [2, 4, 6, 8]; 2 3let sum = 0; 4numbers.forEach((value) => { 5 sum += value; 6}); 7 8console.log("Sum is:", sum); 9
Output:
Sum is: 20
Here, the callback function accepts each value and modifies an outside variable. This pattern is useful when calculating totals, concatenating strings, or checking values in arrays.
When processing array elements, sometimes you also need the element index. Example:
1const fruits: string[] = ["Apple", "Banana", "Cherry"]; 2 3fruits.forEach((fruit, index) => { 4 console.log(`Fruit ${index}: ${fruit}`); 5}); 6
Output:
Fruit 0: Apple
Fruit 1: Banana
Fruit 2: Cherry
Here you can easily display elements along with their index. This becomes especially handy when working with created arrays that need a clear display format.
While foreach loops are great, they have limits:
break
).undefined
, you cannot simply return values.map()
instead of foreach function.1const nums: number[] = [4, 1, 3, 2]; 2 3nums.sort((a, b) => a - b); 4 5nums.forEach((value) => console.log(value)); 6
Output:
1
2
3
4
We sorted the items in ascending order and used a foreach loop to display them. Combining foreach with other array methods like sort or filter can give cleaner, multi-step logic.
When you have arrays of objects, the foreach method becomes even more helpful. For example:
1const users = [ 2 { id: 1, name: "Alice" }, 3 { id: 2, name: "Bob" }, 4 { id: 3, name: "Charlie" } 5]; 6 7users.forEach((user) => { 8 console.log(`User ${user.id}: ${user.name}`); 9}); 10
Output:
User 1: Alice
User 2: Bob
User 3: Charlie
This shows how you can iterate through objects in arrays and access their properties with a clean syntax. This is a common task when dealing with structured API data or configurations.
TypeScript supports multiple javascript data types like numbers, strings, and booleans. The foreach method works the same across them. Example with strings:
1const words: string[] = ["Type", "Script", "Loop"]; 2 3words.forEach((word) => console.log(word.toUpperCase())); 4
Output:
TYPE
SCRIPT
LOOP
This makes it flexible to process different arrays without changing the foreach syntax. For booleans, you could log conditions, and for numbers, you could run calculations.
In projects, you often deal with API responses where you need to iterate through array elements and display values. Example:
1const apiResponse = [ 2 { product: "Laptop", price: 800 }, 3 { product: "Phone", price: 500 }, 4 { product: "Tablet", price: 300 } 5]; 6 7apiResponse.forEach((item, index) => { 8 console.log(`Item ${index + 1}: ${item.product} costs $${item.price}`); 9}); 10
Output:
Item 1: Laptop costs $800
Item 2: Phone costs $500
Item 3: Tablet costs $300
This is an example of how foreach function can simplify displaying elements in structured data.
Sometimes you might work with nested arrays. Foreach can also help here:
1const matrix = [ 2 [1, 2], 3 [3, 4], 4 [5, 6] 5]; 6 7matrix.forEach((row, rowIndex) => { 8 row.forEach((value, colIndex) => { 9 console.log(`Row ${rowIndex}, Col ${colIndex}: ${value}`); 10 }); 11}); 12
This demonstrates how foreach can be used to handle nested data without the need for traditional nested for loops.
The typescript foreach structure is simpler, avoids off-by-one errors, and reads naturally. It reduces boilerplate code while iterating over arrays and improves focus on logic instead of loop mechanics. Developers often appreciate how clean it looks when compared to the verbosity of index-based loops.
💡Want to save even more time? With Rocket.new , you can build any app with simple prompts – no code required. Stop worrying about syntax and start creating.
Using a foreach loop in TypeScript keeps your logic short and clear. Instead of manually managing counters, conditions, and arguments, you rely on the foreach method to handle array elements gracefully. Whether you want to display values, track element index, or just run a callback function, it simplifies the process. Next time you need iteration, try using forEach TypeScript for a more readable flow.