Home Courses Break and Continue Statement in Loops

Break and Continue Statement in Loops

What is break Statement?

  1. Used to stop a loop completely
  2. Loop ends immediately when condition is met


Example: Break in For Loop


for (let i = 0; i < 20; i++) {
if (i == 11) {
break;
}
console.log(i);
}

Output:

0 to 10


When to Use Break?

  1. Stop loop at a specific condition
  2. Example:
  3. Stop at user input
  4. Stop when value is found
  5. Stop based on date/time


What is continue Statement?

  1. Used to skip current iteration
  2. Loop continues with next iteration


Example: Continue in For Loop


for (let i = 0; i <= 10; i++) {
if (i == 4) {
continue;
}
console.log(i);
}

Output:

0 1 2 3 5 6 7 8 9 10

(4 is skipped)


Key Difference


Stops loop completelySkips one step only
Loop endsLoop continues


Example: While Loop with Break & Continue


let i = 0;

while (i < 10) {
i++;

if (i == 3) {
continue;
}

if (i == 8) {
break;
}

console.log(i);
}

Output:

1 2 4 5 6 7


Example: Do While Loop


let i = 0;

do {
i++;

if (i == 3) {
continue;
}

if (i == 8) {
break;
}

console.log(i);

} while (i < 10);

Output:

1 2 4 5 6 7


Common Mistakes

Mistake 1: Wrong Placement of continue


console.log(i);
if(i == 4){
continue;
}


This will still print 4.

Correct:


if(i == 4){
continue;
}
console.log(i);


Mistake 2: Forgetting Increment


while(i < 10){
if(i == 3){
continue;
}
}

This creates an infinite loop.

Always update variable:


i++;

Mistake 3: Confusing Break and Continue

  1. Break stops everything
  2. Continue skips only one step


Can We Use Both Together?

Yes, both can be used in the same loop.

Share this lesson: