Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk1 min

How to Get the Index in a forEach Loop in TypeScript

Pass a second parameter to a TypeScript forEach callback to get the current item’s zero-based index.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the callback’s second parameter: the first is the current item, and the second is its zero-based index.

Get the index with the second callback parameter

const items = ["apple", "banana", "cherry"];

items.forEach((item, index) => {
  console.log(index, item);
});

This logs 0 apple, 1 banana, and 2 cherry. The TypeScript documentation specifies the forEach callback parameters in this order: array element, index, and containing array (TypeScript: Type Compatibility).

As an Amazon Associate I earn from qualifying purchases.

Name the second parameter index or i, whichever makes the code clearest. You can omit it when you only need the item:

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.
items.forEach((item) => {
  console.log(item);
});

Use the third parameter when you need the array

The callback’s optional third parameter is the array being traversed. For example, it can be useful when a callback needs to refer to the current array as well as the item and its position:

items.forEach((item, index, array) => {
  console.log(array[index], item);
});

Choose a different loop only when it fits the task

Use a counted for loop for explicit index control

If you need to manage the index yourself or control loop flow, use a counted loop:

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

With TypeScript’s noUncheckedIndexedAccess option enabled, an indexed array access may be treated as possibly undefined. The forEach callback instead passes the current element directly. See the TypeScript 4.1 release notes for this option.

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

Use for...of when you only need values

A for...of loop gives you each value, but not its index. It is a good fit when position does not matter.

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

Do not confuse for...in keys with the index parameter

for...in iterates keys; for an array, those keys are strings. It is intended for inspecting object properties, not as a substitute for the numeric index supplied to a forEach callback. The TypeScript documentation describes these loop behaviors in Iterators and Generators.

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.

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

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

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.