by Sai gowtham

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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course