How to Stop a For Loop in JavaScript


Borislav Hadzhiev

Sun Oct 10 20212 min read


Photo by Keegan Houser

Stop a For Loop in JavaScript #

Use the break statement to stop a for loop. The break statement exits the current loop and transfers control to the next statement in the program. The break keyword can be used to stop basic for loops, as well as for ... in, for ... of and while loops.

let arr = ['a', 'b', 'c']; for (let index = 0; index < arr.length; index++) { if (arr[index] === 'b') { // 👇️ use break keyword break; } console.log(arr[index]); // 👉️ only logs 'a' }

In the example we use the break statement to terminate the for loop.

The loop only iterates once and finds the array element with a value of b. The if condition is met and we break out of the loop.

We could also use the break keyword in a for ... of loop.

let arr = ['a', 'b', 'c']; for (const element of arr) { if (element === 'b') { break; } console.log(element); // 👉️ a }

We can use the break statement in the following scenarios:

  • basic for loops
  • for ... of loops
  • for ... in loops
  • while loops
  • switch statements

Note that we can't use the break statement when using the forEach method.

The following code throws a SyntaxError: Unsyntactic break.

arr.forEach(element => { if (element === 'b') { break; // 👉️ SyntaxError: Unsyntactic break } });

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.