How to Exit a Loop Before it Completes all Iterations in JavaScript ?
In JavaScript, you can exit a loop before it completes all iterations using the break
statement. The break
statement is used to terminate the loop prematurely based on a certain condition.
Example: Here, the loop prints numbers from 1 to 10. However, when i
becomes equal to 5, the break
statement is executed, causing the loop to terminate immediately.
Javascript
for (let i = 1; i <= 10; i++) { console.log(i); if (i === 5) { console.log( "Exiting the loop early." ); break ; } } |
Output
1 2 3 4 5 Exiting the loop early.