JavaScript

How to Exit a for Loop in JavaScript

An efficient and simple method for executing something repeatedly is to use a loop. In JavaScript, you may frequently need to exit a loop. For instance, it is required to exit the loop iteration through an array of items or any other condition once a particular item is found. To do so, JavaScript permits the use of the “break” keyword.

This post will illustrate the procedure to exit the for loop in JavaScript.

How to Exit a for Loop in JavaScript?

To terminate a for loop in JavaScript, the keyword “break” is used. It terminates a loop or branching expression immediately. When the break statement occurs in a loop, it immediately stops a loop. This keyword is considered an important component of several conditional expressions, such as switches, loops, and so on.

Example 1
In the given example, we will print numbers 0 to 10 integers with the help of the “for” loop. If the iterator variables reaches to the value “i”, the loop will suddenly break or exit due to the “break” statement:

for (i = 0; i < 10; i++) {
 console.log(i);
 if (i == 3) {
  break;
 }
}

As you can see in the output, loop is terminated after printing “3”:

Example 2
First, we will create an object “employee” with properties “name” and “id”:

var employee = [
 { name: 'Susan', id: 1},
 { name: 'Ariely', id: 2},
 { name: 'Mari', id: 3},
 { name: 'Rhonda', id: 4},
 { name: 'Stephen', id: 5},
]

With the help of the for loop, we will print the names of employees. However, if the name is equal to the “Rhonda”, the loop will exit because of the added “break” statement:

for (const e of employee) {
 console.log(e);
 if (e.name === "Rhonda") {
  break ;
 }
}

The output displays the names of employees till the added condition is satisfied:

We have covered all the information related to existing for loop.

Conclusion

To exit a for loop in JavaScript, the keyword “break” is used, which terminates a loop immediately when a particular item is found. It can be utilized to stop the execution control after a specific condition. In this post, we will illustrate the procedure to exit the for loop in JavaScript with detailed examples.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.