How to Break Out of a for Loop in JavaScript
Using the break
statement in JavaScript, you can break out of loops. This immediately stops the loop, which can be useful in certain scenarios.
Here's how:
For Loop
In the common use of a for
loop:
for (var i = 0; i < 10; i++) { console.log(i); if (i === 5) { break; // This will break out of the loop when i equals 5 } }
The loop prints numbers from 0 to 5 and then breaks out of the loop when i
equals 5.
For Of Loop
You can also use the break
statement to exit a for...of
loop in JavaScript just like you would with a for
loop. Here's an example:
const array = [1, 2, 3, 4, 5]; for (const element of array) { console.log(element); if (element === 3) { break; // This will break out of the loop when the element equals 3 } }
The loop iterates over each element of the array [1, 2, 3, 4, 5]
. It prints numbers from 1 to 3 and then breaks out of the loop when the element equals 3.