0% completed
In JavaScript, controlling the flow of loops is crucial for managing how and when loops start, execute, and terminate. This control is achieved through various statements, including label, continue, and break statements. Each serves a unique purpose in enhancing the flexibility and efficiency of loop operations.
Label Statement
A label provides a statement with an identifier that allows you to refer to it elsewhere in your code, particularly with break
and continue
statements. Labels are useful for breaking out of nested loops or continuing a loop iteration at a specific point in nested loops.
Syntax
Parameters
- labelName: Any valid JavaScript identifier.
- statement: Any statement to label.
Example
In this example, we use a label with a break
statement to exit from a nested loop.
This code iterates over a pair of nested loops, but when both i
and j
equal 1, it breaks out of the outer loop entirely, thanks to the outerLoop
label.
Continue Statement
The continue
statement skips the current iteration of a loop and continues with the next iteration. It's particularly useful when a specific condition within the loop doesn't require the execution of the remaining loop body.
Syntax
- Optionally, you can specify a
label
to continue the next iteration of the labeled loop.
Example
Here's how you can use continue
to skip certain iterations in a loop.
This loop prints the numbers 0 to 4, except for 2, because the continue
statement skips the loop's remaining body when i
is 2.
Break Statement
The break
statement terminates the loop immediately when executed. It's used to exit from a loop before it has iterated over all its elements, usually when a certain condition is met.
Syntax
- Just like with
continue
, alabel
can be specified to break out of a specific loop in nested loops.
Beginner Friendly Example
This example demonstrates using break
to exit a loop early.
The loop will print the numbers 0 to 2. When i
equals 3, the break
statement is executed, terminating the loop before all iterations are complete.
Through the use of label, continue, and break statements, JavaScript provides powerful tools for controlling loop execution. These control statements enhance the language's flexibility, allowing for more precise and efficient looping constructs.
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible