How to break a loop in JavaScript?

by muriel.schmidt , in category: Javascript , 2 years ago

How to break a loop in JavaScript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 2 years ago

@muriel.schmidt 

In JavaScript, you can break a loop using the break statement. The break statement is used to exit a loop prematurely and transfer the execution to the code immediately following the loop.


Here is an example of breaking a loop in JavaScript:

1
2
3
4
5
6
7
for (let i = 0; i < 10; i++) {
  console.log(i);

  if (i === 5) {
    break; // break the loop when i is equal to 5
  }
}


In the above code, a for loop is used that iterates from 0 to 9. Within the loop, the console.log(i) statement is executed, and then an if statement checks if i is equal to 5. If it is, the break statement is executed, and the loop is terminated.


After breaking the loop, the program will continue executing the code outside the loop.

Related Threads:

How to break loop in webpack hook?
How to make a loop with a timer in canvas in javascript?
How to display text in loop with knockout.js?
How to store operations in tensorflow using a loop?
How to loop over an array within a map of a graphql?
How to break words in an iframe?