JavaScript

JavaScript break and continue

2 min read Harshit No comments
JavaScript break and continue

When working with loops in JavaScript, sometimes you need to stop the loop or skip a particular iteration.

JavaScript provides two useful statements for this:

  • break
  • continue

Let’s understand both with simple examples.

What is break in JavaScript?

The break statement is used to stop a loop completely.

Once JavaScript reaches break, the loop ends immediately.

Example

for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        break;
    }

    console.log(i);
}

Output

1
2
3
4

When i becomes 5, the break statement runs and the loop stops.

So, 5 to 10 are never printed.

What is continue in JavaScript?

The continue statement is used to skip the current iteration of a loop.

The loop does not stop. It simply moves to the next iteration.

Example

for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        continue;
    }

    console.log(i);
}

Output

1
2
4
5

When i becomes 3, JavaScript skips that iteration and continues with 4.

Difference Between break and continue

The main difference is simple:

StatementWhat it does
breakStops the loop completely
continueSkips the current iteration

Think of it like this:

break → Stop the loop

continue → Skip this one and continue

Example: Using break

Suppose we want to find the number 7 in a loop.

for (let i = 1; i <= 10; i++) {
    if (i === 7) {
        console.log("Number found!");
        break;
    }

    console.log(i);
}

Once 7 is found, there is no need to continue the loop, so we use break.

Example: Using continue

Suppose we want to print only odd numbers.

for (let i = 1; i <= 10; i++) {
    if (i % 2 === 0) {
        continue;
    }

    console.log(i);
}

Output

1
3
5
7
9

Here, continue skips all even numbers.

break and continue with while Loop

Both statements can also be used with while loops.

Using break

let i = 1;

while (i <= 10) {
    if (i === 5) {
        break;
    }

    console.log(i);
    i++;
}

Using continue

Be careful when using continue with a while loop. Make sure the loop variable is updated before continue, otherwise you can create an infinite loop.

let i = 0;

while (i < 5) {
    i++;

    if (i === 3) {
        continue;
    }

    console.log(i);
}

Output

1
2
4
5

Conclusion

The break and continue statements are simple but useful JavaScript features.

Remember:

  • Use break when you want to stop the loop.
  • Use continue when you want to skip the current iteration.
  • Both can be used with for and while loops.

Once you understand these two statements, working with JavaScript loops becomes much easier.

Practice Question

What will be the output of this code?

for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        continue;
    }

    console.log(i);
}

Try to answer before running the code.

Leave a comment

Your email address will not be published.