How to Stop a For Loop in JavaScript


Borislav Hadzhiev

Last updated: Oct 10, 2021


Photo from Unsplash

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.