
Generate React UI with Prompts or Figma Import
Topics
Does foreach return a new value in TypeScript?
Can I break a foreach loop in TypeScript?
What arguments does a foreach callback function accept?
When should I use foreach function instead of map?
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:
array.forEach(callbackFn, thisArg?)
this should refer to inside the callback.To use the typescript foreach loop, the syntax stays consistent with JavaScript:
const numbers: number[] = [1, 2, 3, 4, 5]; numbers.forEach((value, index, array) => { console.log(`Index: ${index}, Value: ${value}`); });
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:
const integers: number[] = [10, 20, 30, 40]; integers.forEach((num) => { console.log(`Number: ${num}`); });
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:
You can also perform operations inside a callback. For example:
Output:
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:
Output:
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:
Output:
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:
Output:
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:
Output:
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:
Output:
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:
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.
undefinedSum is: 20
Fruit 0: Apple
Fruit 1: Banana
Fruit 2: Cherry
breakundefinedmap()1
2
3
4
User 1: Alice
User 2: Bob
User 3: Charlie
TYPE
SCRIPT
LOOP
Item 1: Laptop costs $800
Item 2: Phone costs $500
Item 3: Tablet costs $300
const numbers: number[] = [2, 4, 6, 8];
let sum = 0;
numbers.forEach((value) => {
sum += value;
});
console.log("Sum is:", sum);
const fruits: string[] = ["Apple", "Banana", "Cherry"];
fruits.forEach((fruit, index) => {
console.log(`Fruit ${index}: ${fruit}`);
});
const nums: number[] = [4, 1, 3, 2];
nums.sort((a, b) => a - b);
nums.forEach((value) => console.log(value));
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" }
];
users.forEach((user) => {
console.log(`User ${user.id}: ${user.name}`);
});
const words: string[] = ["Type", "Script", "Loop"];
words.forEach((word) => console.log(word.toUpperCase()));
const apiResponse = [
{ product: "Laptop", price: 800 },
{ product: "Phone", price: 500 },
{ product: "Tablet", price: 300 }
];
apiResponse.forEach((item, index) => {
console.log(`Item ${index + 1}: ${item.product} costs $${item.price}`);
});
const matrix = [
[1, 2],
[3, 4],
[5, 6]
];
matrix.forEach((row, rowIndex) => {
row.forEach((value, colIndex) => {
console.log(`Row ${rowIndex}, Col ${colIndex}: ${value}`);
});
});