How to Break Out of a For Loop in JavaScript
Learn the different methods to break out of a for or for..of loop in JavaScript.
Imagine you have a for loop like this:
1 | const list = ['a', 'b', 'c']; |
If you want to stop the loop at a specific point, for example, when you reach the element ‘b’, you can use the break
statement:
1 | const list = ['a', 'b', 'c']; |
The break
statement can also be used to break out of a for..of loop:
1 | const list = ['a', 'b', 'c']; |
Please note that there is no way to break out of a forEach loop, so if you need to break out of a loop, it is recommended to use either a for loop or for..of loop.
Tags: JavaScript, for loop, break statement, for..of loop