Break

Sometimes you need to stop a loop before it has naturally finished. The break keyword immediately terminates the innermost loop and resumes execution at the next line of code following the loop block.

Using Break

for (let i = 0; i < 10; i++) {
  if (i === 3) {
    // Exits the loop entirely when i reaches 3
    break;
  }
  console.log(i);
}
// Output: 0, 1, 2

Infinite Loops

You can intentionally omit the condition statement in a for loop to create an infinite loop. When doing this, you must use a break statement internally to prevent the program from hanging forever.

// No middle condition means it runs forever!
for (let i = 0; ; i++) {
  if (i === 3) {
    break; // Safely exits
  }
}

Practical Example

A common use case for break is processing items in a batch until a specific capacity or budget is reached.

function itemsWithinBudget(budget) {
  let totalCost = 0;
  let itemsPurchased = 0;
  
  // Infinite loop
  for (let i = 0; ; i++) {
    const itemCost = 1.0 + (i * 0.01);
    
    // If buying this item exceeds the budget, stop the loop
    if (totalCost + itemCost > budget) {
      break; 
    }
    
    totalCost += itemCost;
    itemsPurchased++;
  }
  
  return itemsPurchased;
}