Categories
JavaScript Answers

How to stop a JavaScript for loop?

Spread the love

Sometimes, we want to stop a JavaScript for loop.

In this article, we’ll look at how to stop a JavaScript for loop.

How to stop a JavaScript for loop?

To stop a JavaScript for loop, we can use the break keyword.

For instance, we write

let arr = [1, 2, 3, 4, 5];
for (let ele of arr) {
  if (ele > 3) {
    break;
  }
  console.log(ele);
}

to add a for of loop to loop through the items in the arr array.

In it, we check if the ele variable, which is the item being looped through, is bigger than 3.

If it is, we use break to stop the loop.

Conclusion

To stop a JavaScript for loop, we can use the break keyword.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *