Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JavaScript Break and Continue statements


May 06, 2021 JavaScript


Table of contents


JavaScript Break and Continue statements


The break statement is used to jump out of the loop.

The continue is used to skip an iteration in the loop.


Break statement

We've seen break statements in previous sections of this tutorial. It is used to jump out of a switch() statement.

The break statement can be used to jump out of a loop.

After the continue statement jumps out of the loop, the code after the loop continues to execute, if any:

for (i=0; i <10; i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}

Try it out . . .

Because this if statement has only one line of code, you can omit the parenthesis:

for (i=0;i<10;i++)
{
if (i==3) break;
x=x + "The number is " + i + "<br>";
}


The Continue statement

The continue statement interrupts the iteration in the loop, if a specified condition appears, and then proceeds to the next iteration in the loop. This example skips the value 3:

for (i=0;i<=10;i++)
{
if (i==3) continue;
x=x + "The number is " + i + "<br>";
}

Try it out . . .

Note: Because the break statement is intended to jump out of a block of code, break can be used in loops, switch, and so on, while the role of the continue statement is to move on to the next iteration, so the continue can only be used for loop blocks of code.


JavaScript tag

As you can see in the chapter on switch statements, You can mark JavaScript statements.

To mark a JavaScript statement, add a colon before the statement:

label:
statements

Break and continue statements are simply statements that can jump out of a block of code.

Grammar:

break labelname ;

continue labelname ;

The continue statement (with or without a label reference) can only be used in loops.

Break statements (without tag references) can only be used in loops or switch.

With a label reference, the break statement can be used to jump out of any JavaScript block of code:

cars=["BMW","Volvo","Saab","Ford"];
list:
{
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
break list;
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
}

Try it out . . .

Related articles

Easy to learn JavaScript: JavaScript loop control