Stop For Loop | JavaScript


How to stop for loop in JavaScript?

You can use break to exit for loop in JavaScript. Here is the code to get sum of even numbers.

let count = 0;
for(let i = 0; i < 10; i++){
   if(i % 2 == 0) count+=i;
}
console.log('count is ', count);
// count is 20

Here is how you can stop the loop, the moment 6 is encountered.

let count = 0;
for(let i = 0; i < 10; i++){
   if(i == 6) break;
   if(i % 2 == 0) count+=i;
}
console.log('count is ', count);
// count is 6

As seen above you are using break to stop or exit for loop execution if 6 is encountered.