October 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 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 desk4 min

How to Use TypeScript Loops to Execute Code Multiple Times

Choose the right TypeScript loop for counters, iterable values, object keys, or condition-controlled repetition—and avoid off-by-one and infinite-loop errors.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a loop to repeat a block of TypeScript without writing the same code again. Choose a counted for loop when you need an index or a fixed progression, for...of to process iterable values, for...in to inspect enumerable object keys, and while or do...while when a condition controls repetition.

Choose the loop that matches the job

Need Loop What it gives you
Control a counter, index, or custom step for Initialization, a continuation condition, and an afterthought in one statement.
Process values from an iterable for...of Each value, without manual index management.
Process enumerable object property keys for...in Property keys, not values.
Repeat while a condition is true; zero runs are possible while The condition is checked before each pass.
Run the body once before deciding whether to repeat do...while The condition is checked after each pass.

These forms follow JavaScript iteration-statement semantics. The TypeScript handbook explains the distinction between iterable values and property keys in its Iterators and Generators documentation.

As an Amazon Associate I earn from qualifying purchases.

Repeat a fixed number of times with for

A counted loop is useful when the number of passes, an array index, or a deliberate progression matters:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
for (let i = 0; i < 3; i++) {
  console.log(`Run ${i + 1}`);
}

This prints “Run 1”, “Run 2”, and “Run 3”. The three parts of the loop run in this order:

  1. Initialization: let i = 0 runs once, before the loop begins.
  2. Condition: i < 3 is checked before each pass. If it is false, the body does not run.
  3. Body: the statements inside the braces run when the condition is true.
  4. Afterthought: i++ runs after the body completes, then the condition is checked again.

For an array, use a strict upper bound when iterating by index:

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

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

Array indexes start at zero, so the final valid index is one less than names.length. Using i <= names.length can make the loop attempt to read one position beyond the array. The MDN reference for for documents the loop’s condition and increment behavior.

Process values with for...of

When you need each value and do not need to manage an index, for...of is usually the clearest array loop:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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 = ["Ada", "Grace", "Linus"];

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

Each pass assigns the next value from the iterable to name. Use a counted for instead when the index or step is part of the task.

TypeScript’s output for for...of depends on the project’s target configuration and runtime assumptions. The TypeScript handbook describes native iterator output for ES2015 and newer targets and restrictions or array-specific lowering for ES5. Check the actual project configuration when iterating non-array values for older targets.

Use for...in for enumerable keys

for...in assigns enumerable property keys, so it is suited to inspecting an object’s keys rather than processing an array’s values:

const settings = { theme: "dark", compact: true };

for (const key in settings) {
  console.log(key);
}

For arrays, for...in is not the normal value loop: it yields keys and may also expose custom enumerable properties. Prefer for...of for values, or a counted loop if you need indexes. See the MDN reference for for...in.

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.

Repeat based on a condition with while or do...while

while: check before the body

A while loop can run zero times because it tests its condition before entering the body:

let remaining = 3;

while (remaining > 0) {
  console.log(remaining);
  remaining--;
}

The state used by the condition changes on every pass, so the loop eventually stops when remaining reaches zero.

do...while: run the body first

Use do...while when the body must run at least once before the condition is checked:

let attempts = 0;

do {
  attempts++;
} while (attempts < 1);

The condition is checked after the closing brace. This means the body runs once even if the condition is false after that first pass. MDN’s references explain the behavior of while and do...while.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Skip or stop iterations with continue and break

  • continue ends the current pass and moves to the next one.
  • break exits the loop immediately.

In a counted for loop, continue still proceeds to the afterthought and then checks the condition again. Keep that behavior in mind if you add continue to a loop whose progress depends on an update inside the body: the skipped update may prevent the loop from advancing.

for (let i = 0; i < 5; i++) {
  if (i === 1) {
    continue;
  }
  if (i === 3) {
    break;
  }
  console.log(i);
}

This skips the pass where i is 1 and exits when i reaches 3. The MDN for reference covers how a counted loop proceeds after these control statements.

Avoid loops that never finish

A loop can continue indefinitely if its condition never becomes false and no reachable break exits it. Before running a condition-controlled loop, identify what changes the condition and confirm that every path—including paths containing continue—still allows progress toward the exit.

  • In a counted loop, check that the afterthought moves the counter toward the stopping condition.
  • In a while or do...while loop, update the state that the condition depends on or provide a reachable exit.
  • For arrays, use i < items.length rather than i <= items.length when counting from zero.

For more detail on iteration statements and their behavior, consult the MDN guide to loops and iteration.

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

Use let for a loop counter captured by a closure

A let initializer in a for loop creates a per-iteration binding. That distinction matters when a callback closes over the counter: callbacks created in different passes can retain the corresponding iteration’s value. A counter declared with var, or declared outside the loop and shared, does not provide those separate per-iteration bindings; callbacks can instead observe a later shared value. The TypeScript documentation describes the loop’s let behavior in its iteration documentation.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
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.