break and continuebreak and continue statement in JavaScript

break and continue both statements are used in a loop and they change the working flow of a loop. Let’s discuss them one by one

The break statement is used to break the loop. So, when loop encounters break inside its body it terminates.

break Statement

Let’s discuss the break using the example

Example:

// program to print the value of numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
    // break condition     
    if (i == 4) {
        break; // breaks loop when i becomes 4
    }
    console.log(i);
}

Output:

1
2
3

In the above example, we are printing numbers from 1 to 5 using for loop. But we used a break statement in this example and that is

if(i == 4){
   break;
}

This means that the loop will break when the value of i becomes 4. So when i becomes 4, the condition in if becomes true and the loop ends. No statement is executed after the break statement. Therefore, the output does not contain any values greater than 4, and since if i is 4, the break statement comes before console.log(i), so 4 is not part of the output either.

NOTE: break statement is always used with the conditional statement. To learn more about conditionals visit JavaScript Conditionals

 

continue Statement

Let’s discuss continue with the example

Example:

// program to print the value from 1 to 5
for (let i = 1; i <= 5; i++) {

    // condition to continue    
    if (i == 4) {
        continue;
    }

    console.log(i);
}

Output:

1 
2
3
5

In this example, we are printing value of in each iteration. Notice the continue statement inside loop

if(i == 4){
   continue;
}

This statement means, when the value of i is 4, skip the 4th iteration. Here when i becomes 4, the condition inside if becomes true and continue statement executes, So in 4th iteration it skips all the statements of 4th iteration which comes after continue statement. Since console.log(i) is after continue statement, So it will not print the value of i when i is 4.

NOTE: continue statement is always used with the conditional statement. To learn more about conditionals visit JavaScript Conditionals

NOTE: break statement terminates the loop entirely and continue statement only skips the current iteration.

Thank you so much for reading

Happy Coding

For more details visit MDN Docs

Some other articles on JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *