šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

Using break, continue, and labels in Javascript

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

Note that the break statement does not work in forEach(), as it is meant to be used only withing loop statements and not functions.

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.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *