There are few statements that are used to control loops and switch statements. These statements are used to continue or come out of the loops or switch statement irrespective of the condition. break and continue statements are used to come out of the loop or continue with the next iteration irrespective of the condition.
break
break statement is used to come out of the loop or switch statement early, and execute the next statement after the closing curly braces.
Below is an example for break statement:
for(i=1; i<=10;i++)
{
if (i == 6)
break;
document.write(i + "<br/>");
}
document.write("Exited the loop!");
Output of the above example is:
1
2
3
4
5
Exited the loop!
From the above example and its output, you can see that the control has stopped executing the for loop when the i was equal to 6 and came out of the loop to execute the next statement.
continue
continue statement is used to skip the current iteration and start with the next iteration till the condition is true.
Below is an example for continue statement:
for(i=1; i<=10;i++)
{
if (i == 6)
continue;
document.write("Inside Loop: " + i + "<br/>");
}
document.write("Outside Loop!");
Output of the above example is:
Inside Loop: 1
Inside Loop: 2
Inside Loop: 3
Inside Loop: 4
Inside Loop: 5
Inside Loop: 7
Inside Loop: 8
Inside Loop: 9
Inside Loop: 10
Outside Loop!
You can see from the above example and its output that it has skipped the iteration when i was equal to 6 and continued with the next iteration till the condition is true.