SoFunction
Updated on 2025-04-13

Detailed explanation of common methods for JavaScript to jump out of loops

Preface

Common ways to traverse arrays in JavaScript are:forfor-offorEachmapetc. When we loop the array, in some cases, we will exit the loop early and terminate the iteration, such as: the target element has been found, or a certain condition is met, which can avoid unnecessary calculations and optimize program performance.

1. Common exit loop method

There are two ways to exit the loop in JavaScript:breakandcontinue

  • break: Terminate all loops immediately and execute the code after the loop.
  • continue: Immediately terminate the current loop and start the next loop.

1-1 Use break to break out of the loop

Example:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break; // When i equals 5, the loop will jump out  }
  (i); // Output 0, 1, 2, 3, 4}
('break break out of the for loop');

1-2 Use continue to jump out of the loop

Example:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    continue; // When i equals 5, the current loop is skipped and the next loop is performed  }
  (i); // Output 0, 1, 2, 3, 4, 6, 7, 8, 9, no 5}

2. Can forEach and Map break out of the loop

We have already introduced it aboveforIt can break out of the loop, thenforEachMapCan you break out of the loop?

First we usebreakcontinue;

Example:

const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
_array.forEach((item) => {
  if (item === 5) {
    //break;//Jump target cannot cross function boundary
    //continue;//Jump target cannot cross function boundaryS
  }
  (item);
});

You can seebreakcontinueCannot be used in functions anymore.forEach 、mapA function is set to each element during the loop.

We're tryingreturnmethod.

Example:

//Method 1const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
_array.forEach((item) => {
  if (item === 5) {
    return; // Skip when i equals 5  }
  (item); // 0,1,2,3,4,6,7,8,9
});
//Method 2, use return in the functionfunction testReturn() {
  const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  _array.forEach((item) => {
    if (item === 5) {
      return; // Skip when i equals 5    }
    (item); // 0,1,2,3,4,6,7,8,9
  });
}
testReturn();

returnA statement is used to terminate function execution, and can only jump out of the current function. We checked MDN and found onethrow.

3 powerful throw

throwStatements are used to throw user-defined exceptions. The execution of the current function will be stopped (throwThe subsequent statement will not be executed), and control will be passed to the first one in the call stackcatchpiece.

Example:

let result = 0;
try {
  (
    'First execute the code in the try block, if it throws an exception, the code in the catch block will be executed.  '
  );
  const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  _array.forEach((item) => {
    if (item === 5) {
      throw item; //**Top Error**    }
    (item); //0,1,2,3,4
  });
} catch (e) {
  ('Catch gives e:' + e); //Catch gives e:5  result = e;
} finally {
  ('The code in the finally block is always executed before exiting:' + result); //The code in finally block is always executed before exiting: 5}
(result); //Wait until the value we want is 5

We found that throw can jump out of the loop.

Now let's make a simple summary:

1. Can be usedbreakJust jump out of the loop directly;

2. Can be usedcontinueSkip the current loop and enter the next loop;

3. Can be usedreturnExit the current function execution;

4. Can be usedtry-catch-throwForced exit from the loop.

4. How to exit nested loop

I often encounter some nested data at work. When we find the data we want, in order to save time, we consider how to exit the loop.

4-1 Use break to break out of nested loop

Example:

for (let i = 0; i <= 5; i++) {
  for (let j = 0; j <= 5; j++) {
    if (j === 3) {
      break;
      //continue;
    }

    (`i: ${i}, j: ${j}`);
  }
  // The `break` statement is used to immediately terminate the innermost loop and continue to execute the next statement.  ('Breaking out of break, pointing here');
}

//i: 0, j: 0
// i: 0, j: 1
// i: 0, j: 2
// Bounce out of break and point here// i: 1, j: 0
// i: 1, j: 1
// i: 1, j: 2
// Bounce out of break and point here

breakOnly the innermost loop can be jumped out, but not the multi-layer loop

4-2 Use return to jump out of nested loop

Example:

function testReturn() {
  for (let i = 0; i <= 5; i++) {
    for (let j = 0; j <= 5; j++) {
      if (j === 3) {
        return { i, j };
      }
      (`i: ${i}, j: ${j}`);
    }
  }
}
(testReturn());
//i: 0, j: 0
// i: 0, j: 1
// i: 0, j: 2
// {i: 0,j: 3}

The return statement is used to terminate function execution and can break out of multi-layer loops

4-3 Use try-catch-throw to jump out of nested loop

Example:

let result = 0;
try {
  for (let i = 0; i &lt; 5; i++) {
    for (let j = 0; j &lt; 5; j++) {
      if (j === 3) {
        throw j;
      }
      (`i: ${i}, j: ${j}`);
    }
  }
} catch (e) {
  ('Catch gives e:' + e); //The catch gives e:3  result = e;
}
(result); //3

//i: 0, j: 0
//i: 0, j: 1
//i: 0, j: 2
//The catch gives e:3//3

try-catch-throwMulti-layer loops can also be broken

4-4 Use the tag statement outerLoop

Example:

outerLoop: for (let i = 0; i &lt;= 5; i++) {
  for (let j = 0; j &lt;= 5; j++) {
    if (j === 3) {
      break outerLoop; // Break out of the outer loop    }
    (`i: ${i}, j: ${j}`);
  }
}

//i: 0, j: 0
//i: 0, j: 1
//i: 0, j: 2

In this example,outerLoopis a tag that marks the outer layerforcycle. When the inner layerifWhen the conditions are met,break outerLoop;The statement will jump outouterLoopat the label, thus terminating the execution of the two-layer loop.

Now let's make a simple summary:

1. You can throw nested loops into a function and usereturnJust jump out of the function directly and jump out of the loop;
2. Can be usedbreakCooperateouterLoopBreak out of the loop;
3. Can be usedtry-catch-throwForced exit from the loop.

5. Methods in the array that can end iteration in advance

  • Every: All satisfied.Then just return false and end early.
  • Some: At least one element is satisfied.Then just return true and end early.
  • find, findIndex, include, etc.: end early if the conditions are met;
const _array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
('every');
_array.every((item) =&gt; {
  if (item == 2) {
    return false; //Return false if the condition is not met  }
  (item); //1
});

('some');
_array.some((item) =&gt; {
  if (item == 2) {
    return true; //A satisfying returns true  }
  (item); //1
});

('find');
const found = _array.find((item) =&gt; item === 2);
(found); //2

('findIndex');
const findIndex = _array.findIndex((item) =&gt; item === 2);
(findIndex); //1

6. Final summary

  • Preferential ways to use arrays:includeseverysomewait;
  • Considering usingbreakcontinueBreak out of the loop;
  • returnBounce out of functions is also an option;
  • As for the exceptiontry-catch-throwMulti-layer loops can be exited under special circumstances and are not recommended to use them frequently.
  • at lastouterLoopCombinedbreakUse with caution;

Summarize

This is the article about the common methods of JavaScript to jump out of loops. For more related content on JS to jump out of loops, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!