break

The break statement terminates the current loop, switch statement, or label statement, and transfers program control to the statement immediately following the aborted statement.

In summary: The break statement terminates the current loop, immediately breaking out of the current loop.

Example:

var arr = [1, 2, 3, 4, 5, 6, 7] for (var i = 0; i < arr.length; i++) { if (arr[i] == 4) { break; } console.log(arr[i]); } output: 1,2,3Copy the code

Our common break statements are nested within the current loop to break, the switch statement, and the while statement.

continue

The continue statement terminates the execution of statements in the current iteration of the current loop or marks the loop and continues the loop at the next iteration.

In summary: The continue statement breaks out of the current loop and starts a new loop.

Example:

If we take the example abovebreakInstead ofcontinueWhat would be the result?

var arr = [1, 2, 3, 4, 5, 6, 7] for (var i = 0; i < arr.length; i++) { if (arr[i] == 4) { continue; } console.log(arr[i]); } output: 1,2,3,5,6,7Copy the code

It can be seen that when arr[I] == 4, the cycle stops and a new cycle starts. Note: The continue statement can only be used inside a loop of a while, do/while, for, or for/in. Using it elsewhere will cause an error!

Conclusion:

  • breakTerminates the current loop;
  • continueOut of the current loop and into the next loop, and only within a particular loop body.