How to Exit a Loop in JavaScript?

Estimated read time 1 min read

In JavaScript, you can exit a loop using the break statement. The break statement is used to exit a loop before its natural termination point.

Here’s an example of how to exit a loop in JavaScript using the break statement:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break; // exit the loop when i is equal to 5
  }
  console.log(i);
}

In this example, a for loop is used to iterate over the numbers from 0 to 9. The loop contains an if statement that checks whether the value of i is equal to 5. If i is equal to 5, the break statement is executed, causing the loop to exit early. If i is not equal to 5, the loop continues and the value of i is printed to the console.

It’s worth noting that the break statement can also be used with other types of loops, such as while and do-while loops. Additionally, you can use a labeled break statement to exit nested loops, by specifying the label of the outer loop that you want to exit.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply