How to exit a loop in JavaScript

Last updated: August 28, 2022.

You can escape the execution of a loop in JavaScript by using the break keyword.

For example, let’s say you are iterating through an array of numbers and want to exit the loop when you reach the number 5 in the array.

Here is how you would do it in a for loop:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i=0; i < numbers.length; i++) {
  if (numbers[i] === 5) break;
  console.log(numbers[i]); // 1 2 3 4
}

And here's how you would use break in a for...of loop:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (number of numbers) {
  if (number === 5) break;
  console.log(number); // 1 2 3 4
}

And finally, here's how you would get the same result using a while loop:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let i=0;
while (i < numbers.length) {
  if (numbers[i] === 5) break;
  console.log(numbers[i]); // 1 2 3 4
  i++;
}

Note that the break keyword doesn't work in a for...in loop.

You can learn more about loops by reading our post on the five loops of JavaScript and when to use them.