DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

How to Use `break` in TypeScript `for` Loops

Use `break;` inside a loop to stop as soon as a condition is met. See examples for matches, nested loops, and for...of iteration.

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.

Put break; inside a loop body to stop that loop as soon as a condition is met. Execution then continues with the first statement after the loop. TypeScript uses JavaScript’s loop-control behavior; its type annotations do not change what break does at runtime.

Stop a loop when a condition is met

Usually, place break; inside an if statement in the loop body. When the condition is true, the loop ends immediately. Any remaining statements in that iteration are skipped.

As an Amazon Associate I earn from qualifying purchases.

const values = [3, 7, 12, 18];

for (const value of values) {
  if (value > 10) {
    break;
  }
  console.log(value);
}

console.log("Loop finished");

This prints 3, 7, and then Loop finished. When the loop reaches 12, break skips the rest of that iteration and exits the loop; it does not print 12 or visit 18. The TypeScript Handbook describes break as a way to exit a loop in its discussion of variable declarations: Variable Declaration.

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

Use a loop to stop at the first match

Save the result before breaking if you need to use it after the loop.

const names = ["Ada", "Grace", "Linus"];
let match: string | undefined;

for (const name of names) {
  if (name.startsWith("G")) {
    match = name;
    break;
  }
}

console.log(match); // "Grace"

The loop stops at the first name beginning with G. If no item matches, match remains undefined.

What happens in nested loops?

An unlabeled break exits only the innermost enclosing loop. The outer loop continues with its next iteration.

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
for (const row of [1, 2]) {
  for (const column of [1, 2, 3]) {
    if (column === 2) {
      break;
    }
    console.log(row, column);
  }
}

// Prints: 1 1, then 2 1

Here, each inner loop stops when column reaches 2, but the outer loop still advances to the next row. To leave multiple levels, you can label a loop and use a labeled break, or put the search in a function and return when you find the result. A labeled break exits the labeled statement and the loops nested inside it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
search:
for (const row of [1, 2]) {
  for (const column of [1, 2, 3]) {
    if (row === 2 && column === 2) {
      break search;
    }
    console.log(row, column);
  }
}

Does break work in for...of?

Yes. A for...of loop can be exited with break just like a classic for loop. Use for...of when the loop needs values from an iterable, such as array elements. Use for...in when you need an object’s property keys; it does not serve as a substitute for iterating over array values.

The TypeScript Handbook explains the value-versus-key distinction in Iterators and Generators. For older JavaScript targets, emitted iteration behavior can depend on the target and downlevelIteration settings. See the downlevelIteration TSConfig reference.

Choose the loop form that fits

  • Classic for: Use it when the index or iteration count matters, such as scanning an array by position.
  • for...of: Use it when you need values from an iterable and do not need to manage an index yourself.
  • for...in: Use it when you need property keys, not array values.

Common mistakes and compiler warnings

  • Using break outside a loop or switch: It must appear in a breakable construct.
  • Expecting an inner-loop break to stop every loop: A plain break exits only its innermost enclosing loop.
  • Leaving required work after the break: Statements later in the same iteration are skipped. Put any work that must happen before the exit ahead of break.
  • Breaking unconditionally and then writing more code in the same block: A compiler may flag the following code as unreachable. TypeScript 1.8 release notes describe the allowUnreachableCode option for disabling unreachable-code reporting: TypeScript 1.8 release notes.
  • Assuming TypeScript types alter loop behavior: Types help check your code, but loop control follows JavaScript semantics. The Handbook describes TypeScript as an extension of JavaScript with a type system: TypeScript for JavaScript Programmers.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Using break with a using declaration

If a using variable is declared as part of a for statement, leaving the loop with break disposes of that variable according to the TypeScript Handbook’s Variable Declaration guidance. This matters when the variable represents a resource whose lifetime is managed by using.

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.

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

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.