JavaScript for Beginners
About Lesson

The continue statement in JavaScript is used to skip the current iteration of a loop and continue with the next one. It can be used in forwhile, and do...while loops.

 

Continue in Loops

In loops, the continue statement skips the rest of the loop’s body and continues with the next iteration of the loop.

Here’s an example:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    continue;
  }
  console.log(i);
}

In this example, the number 5 will not be logged to the console because when i equals 5, the continue statement skips the rest of the loop’s body.

 

Continue with the Labeled Statement

A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. The continue statement, when used with a label, allows you to skip to the next iteration of a labeled loop.

Here’s an example:

let i = 0;
let j = 10;
checkiandj: while (i < 4) {
  console.log(i);
  i += 1;
  checkj: while (j > 4) {
    console.log(j);
    j -= 1;
    if ((j % 2) == 0) {
      continue checkj;
    }
    console.log(j + ' is odd.');
  }
  console.log('i = ' + i);
  console.log('j = ' + j);
}

In this example, continue checkj; statement skips the current iteration of the inner loop labeled checkj when j is even.

 

The continue statement in JavaScript provides you with a lot of control over the flow of your code. It allows you to optimize your code and make it more readable and efficient.