How to break a loop in JavaScript?

by muriel.schmidt , in category: Javascript , 8 months ago

How to break a loop in JavaScript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 8 months 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.