JavaScript Break

JavaScript break is special statement that can be used inside the loops, JavaScript break keyword terminates the current loop and execution control transfer after the end of loop.

If label is specified, execution control skip the specified labeled block and control transfer after the end of labeled block.

Note We can't use break keyword to exist a function. break; keyword to exist current loop. And return keyword to exist a function.

JavaScript Break (loop and nested loop example)

General Syntax

break [ label ];

Arguments

  1. break: Required, Keyword for terminates the current loop.
  2. label: Optional, label name skip the specified labelled block.

Syntax

while () {
    break;              // breaks while loop
}
for (;;){
    while () {
        break;          // breaks only while loop
    }
}

Nested loop inside loop: terminates current loop and control transfer after the end of inner label.

outer: {
    inner: {
        for(;;){
            while (){                                     
                break inner;        // break the inner, control transfer to after the end of inner{ .. }
            }
        }                                       
    }                               // end inner
}                                   // end outer

JavaScript Break (while Loop)

Example

<script>
    var i = 0;
    while(i <= 10){
        if (i == 5){
            document.writeln("terminated, i = 5");
            break;
        }
        document.writeln(i);
        i++;
    }
</script>

Run it...   »

JavaScript Break (do..while Loop)

Example

<script>
    var i = 0;
    do {
        if (i == 5){
            document.writeln("terminated, i = 5");
            break;
        }
        document.writeln(i);
        i++;
    } while(i <= 10)
</script>

Run it...   »

JavaScript Break (for Loop)

Example

<script>
    for(var i = 0; i <= 10; i++){
        if (i == 5){
            document.writeln("terminated, i = 5");
            break;
        }
        document.writeln(i);
    }
</script>

Run it...   »

Example (break with labelled block)

<script>
outer: {
    document.writeln("Inside outer start");
    
    inner: {
        for(var i = 1; ;) {
            while(i <= 5){
                document.writeln("i : " + i);             // execute until i = 3
                if (i == 3){
                    document.writeln("Skipped inner");
                    break inner;                          // skip inner block
                }
                i++;
            }
        }
    
    }
    document.writeln("Inside outer end");
}
</script>

Run it...   »

Example Result