How to Stop a For Loop in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 10 20211 min read

banner

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.

index.js
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.

index.js
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.

index.js
arr.forEach(element => { if (element === 'b') { break; // ๐Ÿ‘‰๏ธ SyntaxError: Unsyntactic break } });

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee