Let's take a short look at the basics of using the break
and continue
statements in JavaScript. Also, we will see how labels fit in.
The
break
and
continue
keywords in Javascript
The break keyword is used to exit an iterative for
or while
loop.
For example:
let tBreak = ''
for (let i = 0; i < 5; i++) {
if(i === 4) break
tBreak += `${i} `
}
// 0 1 2 3
The break
statement is also used with switch statements where it does kind of the same things as for loops.
On the other side, continue allows us to skip one iteration step from a for
or while
loop.
In the below example, we will skip the value 2
of the index:
let tContinue = ''
for (let i = 0; i < 5; i++) {
if(i === 2) continue
tContinue += `${i} `
}
// 0 1 3 4
Adding labels to the
break
and
continue
commands
One less-known fact is that we can add labels so that we can point out where break
or continue
will go when executed.
In order to define a Javascript label we need to assign it to an iterative loop:
myLabel:
for (let i = 0; i < 5; i++) { ... }
// or
myLabel: for (let i = 0; i < 5; i++) { ... }
No other code is allowed between a label and its corresponding loop:
// ⛔️ this will not work
myLabel:
console.log('something')
for (let i = 0; i < 5; i++) { ... }
Not respective this will lead to an undefined label error being throwed.
After a label is defined we can pass it to a break
or continue
statement:
myLabel: for (let i = 0; i < 5; i++) {
if(i === 1) break myLabel;
}
Labels become more useful when we have to work with multiple nested loops and we can point to what label to jump. For example:
let tLabels = ''
lableForI: for (let i = 0; i < 3; i++) {
lableForJ: for (let j = 0; j < 3; j++) {
if(j === 1) continue lableForI;
tLabels += ` (${i}, ${j}) `
}
}
// (0, 0) (1, 0) (2, 0)
Note that you can jump only to the labels that were defined before the usage of the break
or continue
:
// ⛔️ this will not work
myLabel1: for (let i = 0; i < 5; i++) {
continue myLabel2;
}
myLabel2: for (let j = 0; j < 5; i++) {}
As usual, I have made a codepen for this example and you can check it out here.
The post Using break, continue, and labels in Javascript appeared first on Js Craft.