Understanding Break VS Continue in For loop.

These are concepts in JavaScript that can be easily intertwined. Just like anything I have written about in the past, you don't have to have it stick to your head, you however just need to be able to differentiate the differences, and use cases, then when the need arise to use it in your code, you have Google or your notepad or references like this page to give a refresher on the topics so you're not stuck or confused in your code.

Here's an example and use case for Continue;

I want to print to the console output of even numbers from 0 to 30, but I want to ensure the numbers divisible by 5 or 12 are "skipped", here's how I would use the continue syntax.

for (let i = 0; i < 30; i += 2 ){
    if(i == 11 || i % 5 == 0){
        continue;
    }
    console.log(i)
}

//Output would be 2 through 28, but it would "skip" the number 12
// and any other number divisible by 5. 
// Think of Continue as "skip" the presently set condition but complete the loop.

Break on the other hand would "break" or end the loop once the set condition is met.

example; I want to print to the console output of odd numbers from 0 to 30, but I want to ensure that once I reach the number 7, I want to end the loop. Here's how I would use the break syntax.

for (let i = 0; i < 30; i++ ){
    if(i % 2 == 0){
         continue;
    }else if(i == 7){
        console.log(i); //Comment out this line to see the result.
        break;
    }
    console.log(i)
}

//Output would be 1, 3, 5, and 7.

Like and share if you learned something today. Learn JavaScript one topic every day.