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:
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”:
{ 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:
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.