How to Use TypeScript Loops to Execute Code Multiple Times

When I build a support-ticket dashboard, I often need to display every ticket returned by an API, calculate totals, or flag overdue requests. Writing the same code for every ticket would become impossible to maintain. That is where TypeScript loops help you execute code multiple times without repeating yourself.

TypeScript is JavaScript with optional static types. A loop repeats a block of code while a condition remains true or while values remain available in a collection. In this guide, I will use a small support-ticket dashboard example to show the loops you will use most.

What Are TypeScript Loops?

A loop lets your program repeat an action. You might use one to:

  • Render support tickets in a dashboard
  • Process API activity logs in a Node.js service
  • Validate uploaded records in an automation script
  • Calculate the total value of transaction records
  • Send a reminder for each overdue ticket

An array is an ordered collection of values. For example, this string[] array stores ticket titles:

const ticketTitles: string[] = [
"Login issue",
"Payment failed",
"Export report error"
];

The string[] type tells TypeScript that every item in ticketTitles must be a string. If you are new to typed collections, this guide on initializing arrays in TypeScript is a useful starting point.

Use a for Loop in TypeScript

The classic for loop works best when you need the current position of each item. That position is called an index, and arrays start counting at index 0.

const ticketTitles: string[] = [
"Login issue",
"Payment failed",
"Export report error"
];

for (let index = 0; index < ticketTitles.length; index++) {
console.log(`${index + 1}. ${ticketTitles[index]}`);
}

This code runs three times because ticketTitles.length equals 3. Each time, index increases by one, and the code reads the matching item from the array.

The output is:

1. Login issue
2. Payment failed
3. Export report error

You can see the output in the screenshot below.

TypeScript Loops to Execute Code Multiple Times

Use a regular for loop when you need the index for numbering, comparisons, or access to nearby array values. For more array-focused examples, see TypeScript for loops with arrays.

Understand the Three Parts

A standard for loop has three sections:

for (initialValue; condition; update) {
// Repeated code
}

Here is what each section does:

  • let index = 0 creates the counter.
  • index < ticketTitles.length controls how long the loop runs.
  • index++ adds one to the counter after every run.

Always use < array.length, not <= array.length. The last valid index is one less than the array length.

const priorities: string[] = ["High", "Medium", "Low"];

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

This produces undefined on the final iteration because priorities[3] does not exist.

Use for…of Loops to Execute Code Multiple Times

A for…of loop gives you each array value directly. I use it most when I only need the item itself and not its index.

const ticketTitles: string[] = [
"Login issue",
"Payment failed",
"Export report error"
];

for (const title of ticketTitles) {
console.log(`Open ticket: ${title}`);
}

You can see the output in the screenshot below.

Use TypeScript Loops to Execute Code Multiple Times

This loop reads naturally: “for each title in ticket titles.” It avoids array index syntax, so it often makes code easier to scan.

Use const because the loop variable receives a new value on each iteration but your code does not need to reassign it. Learn more in this guide to for…of loops in TypeScript.

Loop Through Typed Objects

Dashboard data usually contains objects rather than plain strings. An interface defines the expected shape of an object.

interface SupportTicket {
id: number;
title: string;
priority: "High" | "Medium" | "Low";
isOpen: boolean;
}

const tickets: SupportTicket[] = [
{ id: 101, title: "Login issue", priority: "High", isOpen: true },
{ id: 102, title: "Payment failed", priority: "High", isOpen: true },
{ id: 103, title: "Export report error", priority: "Medium", isOpen: false }
];

for (const ticket of tickets) {
if (ticket.isOpen) {
console.log(`${ticket.id}: ${ticket.title} (${ticket.priority})`);
}
}

The SupportTicket[] type protects your data structure. TypeScript will warn you if you miss a required property or assign an invalid priority. For a deeper look at object arrays, read arrays of objects in TypeScript.

Use forEach() for Array Actions

The forEach() method runs a callback function once for every item in an array. A callback is a function that another function calls later.

const ticketTitles: string[] = [
"Login issue",
"Payment failed",
"Export report error"
];

ticketTitles.forEach((title: string, index: number) => {
console.log(`${index + 1}: ${title}`);
});

This code prints every ticket title with its number. The forEach() method handles iteration, while your callback handles the work.

For short display or logging tasks, forEach() keeps code compact. However, do not use it when you must stop early with break or continue. A regular for loop or for...of loop handles those cases better. You can explore this syntax further in TypeScript forEach method on arrays.

Pro Tip: I use for...of instead of forEach() whenever a loop may need to stop early. It keeps break, continue, and async workflow handling predictable in real dashboard and API code.

Use while Loops When a Condition Controls Repetition

A while loop repeats while a condition evaluates to true. It works well when you do not know the exact number of iterations before the loop starts.

For example, imagine a Node.js script that processes support tickets in pages of 100 records until an API returns no more records.

let pageNumber: number = 1;
let hasMoreTickets: boolean = true;

while (hasMoreTickets) {
console.log(`Fetching ticket page ${pageNumber}`);

// Replace this with an API request in a real application
const returnedTicketCount: number = pageNumber < 4 ? 100 : 0;

if (returnedTicketCount === 0) {
hasMoreTickets = false;
}

pageNumber++;
}

This loop runs until hasMoreTickets becomes false. The condition must change inside the loop. Otherwise, you create an infinite loop, which means code repeats forever and can freeze a browser tab or consume server resources.

let attempts: number = 0;

while (attempts < 3) {
console.log(`Attempt ${attempts + 1}`);
attempts++;
}

This example runs exactly three times because attempts++ updates the condition value.

Use do…while When Code Must Run Once

A do…while loop runs its code block first and checks the condition afterward. It always runs at least once.

let retryCount: number = 0;
let connectionActive: boolean = false;

do {
retryCount++;
console.log(`Trying connection ${retryCount}`);

connectionActive = retryCount === 2;
} while (!connectionActive && retryCount < 3);

This pattern helps with retry logic. Your application must attempt the connection once before it knows whether another attempt is necessary.

Use do...while sparingly. Most application loops read more clearly as for, for...of, or while loops. See more examples in TypeScript do…while loops.

Control TypeScript Loops With break and continue

Two keywords give you more control inside loops:

  • break stops the entire loop immediately.
  • continue skips the current iteration and moves to the next one.

Stop When You Find a Match

Suppose the dashboard needs to find a specific high-priority ticket.

interface SupportTicket {
id: number;
title: string;
priority: "High" | "Medium" | "Low";
isOpen: boolean;
}

const tickets: SupportTicket[] = [
{ id: 101, title: "Login issue", priority: "High", isOpen: true },
{ id: 102, title: "Payment failed", priority: "High", isOpen: true },
{ id: 103, title: "Export report error", priority: "Medium", isOpen: false }
];

for (const ticket of tickets) {
if (ticket.id === 102) {
console.log(`Found: ${ticket.title}`);
break;
}
}

You can see the output in the screenshot below.

How to Use TypeScript Loops to Execute Code Multiple Times

After the loop finds ticket 102, break prevents unnecessary work on later records. Read more about breaking out of TypeScript loops.

Skip Closed Tickets

Use continue when you want to ignore certain values but keep processing the rest.

for (const ticket of tickets) {
if (!ticket.isOpen) {
continue;
}

console.log(`Notify support team: ${ticket.title}`);
}

The loop skips the closed ticket and only logs the open ones. This approach keeps the main work lower in the loop and easier to read. You can see additional patterns in this guide on the continue statement in TypeScript for loops.

Choose the Right TypeScript Loop

Each loop solves a slightly different problem.

LoopBest use caseIndex available?Can use break?
forYou need an index, counter, or custom incrementYesYes
for...ofYou need each array value directlyNot directlyYes
forEach()You need a short action for every array itemYes, as callback parameterNo
whileA changing condition controls repetitionOptionalYes
do...whileCode must run at least onceOptionalYes

For everyday arrays, start with for...of. Choose a standard for loop when the index matters. Use while for retries, pagination, and condition-based automation.

Loop Through API Results Safely

A real dashboard often receives JSON from an API. Validate the shape before relying on object properties, especially when data comes from outside your application.

interface SupportTicket {
id: number;
title: string;
priority: "High" | "Medium" | "Low";
isOpen: boolean;
}

function displayOpenTickets(tickets: SupportTicket[]): void {
for (const ticket of tickets) {
if (!ticket.isOpen) {
continue;
}

console.log(`[${ticket.priority}] ${ticket.title}`);
}
}

const apiTickets: SupportTicket[] = [
{ id: 201, title: "Cannot reset password", priority: "High", isOpen: true },
{ id: 202, title: "Invoice download issue", priority: "Medium", isOpen: true },
{ id: 203, title: "Old account request", priority: "Low", isOpen: false }
];

displayOpenTickets(apiTickets);

The : void return type says the function performs an action but does not return a value. Typed function inputs help you catch data mistakes before code runs. If API data might fail or return an unexpected shape, add exception handling in TypeScript around the request and validation logic.

Avoid placing await inside forEach(). The method does not wait for asynchronous callbacks in the way most developers expect. For sequential API calls, use for...of.

async function notifyOpenTickets(tickets: SupportTicket[]): Promise<void> {
for (const ticket of tickets) {
if (!ticket.isOpen) {
continue;
}

await sendNotification(ticket);
}
}

async function sendNotification(ticket: SupportTicket): Promise<void> {
console.log(`Notification sent for ticket ${ticket.id}`);
}

This loop waits for each notification before sending the next. That behavior helps when an API has rate limits or requests must happen in order.

Things to Keep in Mind

  • Avoid infinite loops: Update the value used in a while or do...while condition, or the loop may never stop.
  • Use array length carefully: Write index < items.length, not index <= items.length, to avoid reading an undefined item.
  • Pick for…of for clarity: Use it when you only need each value and not its index.
  • Do not use break in forEach(): forEach() does not support break or continue; use for...of when you need control flow.
  • Avoid async forEach() mistakes: Use for...of for sequential asynchronous tasks, or Promise.all() when independent tasks should run together.
  • Keep loop work focused: Move complex logic into typed functions so each loop remains easy to test and maintain.

Frequently Asked Questions

What are the different loops in TypeScript?

TypeScript supports JavaScript loop syntax, including for, for...of, for...in, while, and do...while. It also supports array methods such as forEach(). Choose the loop based on whether you need values, indexes, object keys, or condition-based repetition.

How do I loop through an array in TypeScript?

Use for...of when you want every value in an array.
const names: string[] = ["Asha", "Ravi", "Mina"];
for (const name of names) {
console.log(name);
}

Use a regular for loop when you also need the numeric index.

What is the difference between for…of and forEach() in TypeScript?

for...of is a loop statement that supports break, continue, and sequential await operations. forEach() is an array method that runs a callback for every item. Use for...of when control flow matters, and use forEach() for short, simple actions.

Can I use break in a TypeScript forEach loop?

No. break only works inside loop statements such as for, for...of, and while. Use for...of if you need to stop after finding a matching item.

How do I stop an infinite loop in TypeScript?

Ensure the loop condition eventually becomes false. In a while loop, update the counter, retry count, response value, or other condition variable inside the loop. Add a maximum number of attempts for retry-based automation.

Should I use for…in to loop through an array in TypeScript?

Avoid for...in for normal arrays because it iterates property keys as strings, not values. Use for...of, forEach(), or a standard for loop instead. Use for...in mainly when you need to iterate over an object’s enumerable keys.

TypeScript loops give you a reliable way to process arrays, API records, dashboard data, and automation tasks without duplicating code. Start with for...of for readable array processing, then use for, while, or forEach() when their specific strengths match the job.

You May Also Like

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.