BREAK AND CONTINUE STATEMENT IN JAVASCRIPT
The break
statement is used to break or jump out of the javascript loops ( like for loop, while
loop and do...while loop ) and switch statements.
The continue
statement is used to skips the execution of the program to the next iteration.
Let's see the flow diagram of both break
and continue
statements.
Break statement flow diagram
continue statement flow diagram
In the above images you can see comparison between break
and continue
statements.
The break
and continue
statements are used inside conditional statements, so when certain condition statisfy you can choose to
break
the loop or choose to continue
to next iteration.
Javascript break statement
Javascript break
statement helps use to exit out of the loop when certain condition satisfies.
For example: we want to exit a loop when our initialize or some variable achieve a value, then we can check
for that condition and if condition statisfies then use break
statement to exit out of the loop.
We have already seen the break
statement when we were learning switch statement. The break
statement was used there to jump out of
switch statement.
Here is an example of a break
statement which jumps out of loop when count (some variable)
becomes equal to 4.
Javascript continue statement
The continue
statement is used to jump one iteration of the loop, means you can skip one time
execution of the loop using it. For example: while executing a loop if you want not to work on a variable for
some value 4, then you can simply skip it by using continue
statement.
In the example below continue statement executes when count is equal to 4, and skip the code below it without executing.
break
and continue
statements can't be used in forEach, map,
reduce, etc because these are functions and break and continue can only be used in loops.
Javascript label statement
Javascript labelled code represents a block of code where the label name is used to identify the block of code.
The label
name should not be a reserved keyword in javascript. like true, false, for, etc.
Syntax:
label_name: // Single or Multiple Code // Statements
A label
name can be used to break
or continue
the block of code.
break label_name; continue label_name;