- Abstract class
- Annotations
- Array
- Asserts
- Class
- Const
- Decorators
- Default parameter
- Dictionary
- Enum
- For loop
- forEach()
- Function
- Generics
- Index signature
- Infer
- Inheritance
- Interface
- Let
- Map type
- Mixin
- Module
- Namespace
- Never
- Object type
- Operator
- Optional parameter
- Promise
- Property
- Tuples
- Type alias
- Type guard
- Type narrowing
- Union
- Utility types
- Var
- Void
TYPESCRIPT
TypeScript forEach: Syntax, Usage, and Examples
The TypeScript foreach
method allows you to loop through arrays and execute a function on each element. It’s a clean, readable way to handle tasks like printing values, transforming data, or triggering side effects—without writing a traditional for-loop.
How to Use foreach in TypeScript
You can use forEach
directly on any array. The syntax takes a callback function that receives the current element, its index, and the array itself.
Basic Syntax of TypeScript forEach
array.forEach((element, index, array) => {
// Your code here
});
Here’s a simple example:
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit) => {
console.log(fruit);
});
This prints each fruit to the console—no loop counters, no setup, just clean iteration.
When to Use foreach TypeScript Style
Reach for forEach
in TypeScript when:
- You want to perform an action on each item in an array.
- You’re logging values or applying side effects.
- You need a readable, functional approach over classic
for
orwhile
loops. - You're chaining operations like
filter()
andmap()
but still want a side-effect-based step.
The forEach
method fits naturally into most frontend or backend TypeScript workflows.
Examples of TypeScript forEach in Practice
Logging Each Value in an Array
const names = ['Liam', 'Ava', 'Noah', 'Emma'];
names.forEach((name) => {
console.log(`Hello, ${name}!`);
});
You’re iterating over the list and saying hello to each name.
Accessing Both Index and Value
You can use forEach
with index by adding a second argument:
const items = ['pen', 'notebook', 'eraser'];
items.forEach((item, index) => {
console.log(`${index + 1}: ${item}`);
});
This helps when you need to display ordered lists or debug specific elements.
Using forEach with TypeScript Interfaces
interface Product {
name: string;
price: number;
}
const cart: Product[] = [
{ name: 'T-shirt', price: 25 },
{ name: 'Shoes', price: 60 }
];
cart.forEach((product) => {
console.log(`${product.name}: $${product.price}`);
});
TypeScript forEach
plays well with typed arrays, giving you autocompletion and type safety.
Modifying External Variables
While forEach
can’t return a value like map
, it can interact with variables outside the function:
let total = 0;
const prices = [20, 30, 50];
prices.forEach((price) => {
total += price;
});
console.log(`Total: $${total}`);
You’re not mutating the array—just using forEach
for side effects.
Learn More About foreach in TypeScript
Difference Between forEach and map
Both forEach
and map
loop through arrays, but they serve different purposes.
foreach
is for side effects. It doesn't return a new array.map
is for transforming data. It returns a new array with modified elements.
// Using map
const lengths = ['dog', 'cat', 'horse'].map(animal => animal.length);
// [3, 3, 5]
// Using forEach (no returned array)
const lengths2: number[] = [];
['dog', 'cat', 'horse'].forEach(animal => lengths2.push(animal.length));
If you need a result, use map
. If you’re just doing something with each element, forEach
is ideal.
Chaining Methods with forEach
You can chain filter()
and forEach
to apply an action to a subset of values:
const scores = [90, 70, 85, 60, 95];
scores
.filter(score => score >= 80)
.forEach(score => console.log(`Passing score: ${score}`));
This example filters the high scores, then logs only those using forEach
. It’s a clean, readable pattern.
You can also chain find()
and forEach
, though it's less common since find()
returns a single item:
const books = [
{ title: '1984', author: 'Orwell' },
{ title: 'Brave New World', author: 'Huxley' }
];
const book = books.find(b => b.title === '1984');
[book].forEach(b => {
if (b) console.log(b.author);
});
This is helpful if you want to apply a block of logic even when find()
returns just one item.
Using foreach with Object Keys
While forEach
is built for arrays, you can apply it to object properties by using Object.keys()
or Object.entries()
:
const user = {
name: 'Alice',
age: 30,
country: 'Canada'
};
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
This lets you iterate over object data using array logic.
Typescript foreach With Index on Filtered Array
const scores = [88, 76, 92, 55];
scores
.filter(score => score >= 80)
.forEach((score, index) => {
console.log(`#${index + 1}: ${score}`);
});
The index reflects the filtered array, not the original—useful for scoring or ranking.
Working with Optional Chaining and Null Values
TypeScript helps prevent runtime errors by checking types, but forEach
still needs a non-null array. If you’re unsure whether the array is defined, use optional chaining:
const users: string[] | undefined = ['John', 'Jane'];
users?.forEach(user => {
console.log(`Welcome, ${user}`);
});
This avoids “cannot read property 'forEach' of undefined” errors.
Best Practices for Using foreach in TypeScript
- Avoid using
forEach
when you need to return a transformed array—usemap
instead. - Don’t use
break
orcontinue
inside aforEach
. It doesn’t support exiting early. - Keep your callback functions pure unless you're explicitly doing side effects.
- Use arrow functions for concise syntax unless you need
this
context. - If your logic gets complex, extract the callback into a named function for clarity.
- Use
forEach
with index when order matters or you’re labeling elements.
The forEach
TypeScript method offers a straightforward, readable way to loop through arrays. Whether you're displaying items, calculating totals, or triggering animations, it keeps your code compact and expressive.
With support for types, interfaces, and chaining with filter()
or map()
, TypeScript forEach
is a tool you’ll reach for again and again. Use it when clarity matters and when you're focused on side effects, not transformations.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.