Open In App

What is the use of the Break Statement in a Loop in JavaScript ?

The break statement in JavaScript is used to prematurely terminate a loop, allowing the program to exit the loop before the normal loop condition is met. It is often used to interrupt the loop execution based on certain conditions.

Example: Here, the while loop will continue indefinitely (since the condition is true). However, the if statement inside the loop checks if the counter is equal to 3. When this condition is met, the break statement is executed, causing the loop to terminate immediately.




let counter = 1;
 
while (true) {
    console.log(counter);
 
    if (counter === 3) {
        console.log("Breaking out of the loop.");
        break;
    }
 
    counter++;
}

Output
1
2
3
Breaking out of the loop.
Article Tags :