Loops are a fundamental concept in programming that allow you to repeat a block of code multiple times. The for loop is one of the most common types of loops in JavaScript. Sometimes you may want to exit or break out of a for loop prematurely based on a certain condition. Here are a few ways to exit a for loop in JavaScript.

Using the break Statement

The simplest way to exit a for loop in JavaScript is to use the break statement. Here is the syntax:

for (initialization; condition; update) {
  // code block to be executed

  if (someCondition) {
    break; 
  }
}

The break statement immediately terminates the current loop and continues executing the code after the loop.

Here is an example:

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

// Outputs:
// 0
// 1
// 2 
// 3
// 4

As you can see, once i equals 5, the break statement is executed which exits the loop. So 5 to 9 are not logged.

You can exit based on any condition, like finding a particular value in an array:

const numbers = [1, 2, 3, 4, 5, 6];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === 4) {
    break;
  }
  console.log(numbers[i]);   
}

// Outputs: 
// 1
// 2
// 3

Once the number 4 is reached, the loop exits even though there are still array elements left.

Using a Loop Variable

Another method is to set up an external loop variable that controls execution of the loop:

let exitLoop = false;

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    exitLoop = true;
  }

  if (exitLoop) {
    break; 
  }

  console.log(i);
} 

Here a variable exitLoop is used to control when the loop exits. Once exitLoop is set to true, the second if statement catches it and breaks out of the loop.

Returning from Inside a Loop

In JavaScript functions, you can simply return from inside a loop to exit it which also exits the current function.

For example:

function findNum(nums) {
  for (let i = 0; i < nums.length; i++)  {
    if (nums[i] === 5) {
      return nums[i]; 
    }
  }
}

findNum([1, 3, 5, 7]); // Returns 5

When 5 is found, it immediately returns that value and exits both the loop and function.

So in summary, use break to exit a loop but keep executing additional code, return to exit both a loop and function, or use an external variable to control execution. All three are handy techniques for prematurely exiting JavaScript for loops.

Similar Posts

Leave a Reply

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