How to stop a for loop in JavaScript
In this tutorial, we will learn about how to stop a for loop early in JavaScript.
Consider we have a for loop which is looping through the array of items.
const arr = [10, 25, 46, 90, 52];
for (let i= 0; i < arr.length; i++){
console.log(arr[i]);
}
To stop a for loop when we reach to the element 46
, we can use the break
statement in JavaScript.
const arr = [10, 25, 46, 90, 52];
for (let i= 0; i < arr.length; i++){
if(arr[i] === 46){
break; }
console.log(arr[i]);
}
Similarly, we can use the break statement to stop the for..of and for..in loops
const arr = [10, 25, 46, 90, 52];
// for .. in
for (let i in arr){
if(arr[i] === 46){
break;
}
console.log(arr[i]);
}
// for .. of
for (let i of arr){
if(i=== 46){
break;
}
console.log(i);
}
Note: The break statement doesn’t work on
Array.forEach()
method.