How to break a loop in JavaScript?

by , 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 

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:

for (let i = 0; i < 10; 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.