October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Loop Through an Array in TypeScript

Use for...of for array values, an indexed for loop when position matters, and map or filter to create transformed or selected arrays.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a straightforward pass over an array’s values, use for...of:

const names: string[] = ["Ada", "Grace", "Linus"];

for (const name of names) {
  console.log(name);
}

TypeScript infers name as the array’s element type. Choose an indexed loop when you need positions, or an array method when you want to transform or select elements.

As an Amazon Associate I earn from qualifying purchases.

Choose the loop that matches the task

What you need Use Why
Read each value, with ordinary loop control for...of Provides each element directly; supports break and continue.
Use an element’s position or assign to an array slot Indexed for loop Gives access to the index as well as the element.
Run a callback for each element, without needing early exit forEach Concise callback-based traversal.
Create a transformed array map Returns a new array containing callback results.
Keep elements that meet a condition filter Returns a new array containing selected elements.

Loop through values with for...of

Arrays are iterable, so for...of visits their values in order. Use it when you need each element but not its numeric position:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const scores: number[] = [88, 94, 79];

for (const score of scores) {
  console.log(score);
}

Because this is a loop statement, you can skip an item with continue or stop the loop with break:

for (const score of scores) {
  if (score < 80) continue;
  if (score >= 90) break;
  console.log(score);
}

The TypeScript handbook describes an iterable as an object with an implementation of Symbol.iterator. Its Iterators and Generators handbook page also distinguishes for...of, which yields values, from for...in, which yields property keys.

Use an indexed loop when you need positions

A numeric loop is useful when the index matters, such as when displaying numbered entries or updating a slot:

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
const names: string[] = ["Ada", "Grace", "Linus"];

for (let i = 0; i < names.length; i++) {
  console.log(i, names[i]);
}

With noUncheckedIndexedAccess enabled, TypeScript treats an indexed lookup such as names[i] as potentially undefined. A bounds check in the loop condition does not necessarily remove that possibility from the type. The TypeScript 4.1 release notes explain this behavior and suggest using for...of or forEach when the index is not needed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use forEach for callback-based traversal

When each element needs an action but the operation does not need to stop the loop early, forEach is a callback alternative:

names.forEach((name, index) => {
  console.log(index, name);
});

The callback receives the value and can also receive its index. Unlike a loop statement, forEach does not offer the same straightforward break or continue control; use for...of if you need to exit early.

Use map to transform or filter to select

Build a new array with map

Use map when the result should contain one transformed value for each input element:

const nameLengths = names.map(name => name.length);

This returns a new array; it is not just a loop for performing an action without using its results.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep matching values with filter

Use filter when you want a new array containing only elements that satisfy a condition:

const passingScores = scores.filter(score => score >= 80);

In TypeScript 5.5 and later, qualifying filter callbacks can benefit from inferred type predicates. For example, filtering out undefined can narrow the resulting element type. This inference applies when TypeScript can establish the predicate from the callback; it is not a guarantee for every conditional expression. See the TypeScript 5.5 release notes.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why for...in is usually the wrong array loop

for...in enumerates property keys, so with an array it gives keys such as "0", "1", and "2"—not the element values. Use it only when you intentionally need to enumerate keys; for array values, prefer for...of. The distinction and examples are in the TypeScript iterators documentation.

Check target and runtime support for older environments

for...of relies on the iterable protocol. The TypeScript handbook notes that when targeting ES5, iterators are permitted only for arrays unless downlevelIteration is enabled. That compiler option changes emitted code to use a helper that checks for native or polyfilled Symbol.iterator, with fallback behavior if it is unavailable. Consult the TSConfig reference for downlevelIteration alongside the handbook’s iterators guidance.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a normal array in a modern runtime, for...of is a clear default. If the project targets an older environment or loops over a non-array iterable, verify the TypeScript target, whether downlevelIteration is enabled, and whether the runtime provides Symbol.iterator. TypeScript 5.6 documents the protocol-related Iterable, Iterator, and IteratorObject types in its release notes.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.