This page looks best with JavaScript enabled

Break and Continue in Javascript

 ·   ·  ☕ 2 min read

Javascript does not have goto - thankfully. But it has continue and break that more or less perform the same function.

If for any reason you want to jump out of a loop, here’s how you can do that -

1
2
3
4
for (let i = 0; i < 10; i++) {
  console.log("i is", i);
  if (i > 1) break;
}

But, what if you want to jump to a particular statement? That’s where break can help.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
outerloop: for (let i = 0; i < 10; i++) {
  console.log("i is", i);
  innerloop: for (let j = 0; j < 10; j++) {
    console.log("j is", j);
    if (j > 1) break outerloop;
  }
}

/* output
i is 0
j is 0
j is 1
j is 2
*/

Similar to break, you can use continue to continue loop.

1
2
3
4
5
for (let i = 0; i < 10; i++) {
  console.log("i is", i);
  if (i % 2 == 0) continue;
  // no op for even numbers
}

And, when used with labels..

1
2
3
4
5
6
7
outerloop: for (let i = 0; i < 10; i++) {
  console.log("i is", i);
  innerloop: for (let j = 0; j < 10; j++) {
    console.log("j is", j);
    if (j > 1) continue innerloop;
  }
}

Final words

Just use conditional statements to execute logic as normal. There is no place for labels in this day and age.

  • Do not use continue - ever
  • Use break to break out of the inner loop, but never with labels
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things