Skip to content

JavaScript break nested loop | Example code

  • by

JS break statement in loop breaks the current loop only, not all of them. You have to use a boolean variable to break (break nested loop) out of the enclosing loop in JavaScript.

By default, the only innermost loop is escaped but you can achieve the behavior you expect by a self-enclosing function and a return statement.

    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            if (i == 3) {
            document.write(i + '*' + j + '<br>');

Example break the nested loop in JavaScript

Simple example code.

<!DOCTYPE html>
    let b = false
    for (i = 0; i < 5; i++) {

      for (j = 0; j < 2; j++) {

        if (i == 2) {
          b = true;
      if(b) break



JavaScript break nested loop

Do comment if you have any doubts or suggestions on this JS break loop topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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