JavaScript label

JavaScript label mainly use with break and/or continue statement. JavaScript label is unique name as an identifier for a statement.

In JavaScript, ECMA hasn't specified goto statement like in other programming languages, so you have to use labels along with break or continue statement.

General Syntax

label:
label: {
                    // Scope of the block
}

Arguments

  1. label: Required, unique name as an identifier for referring to label that are specified with break or continue statement.
  2. { .. }: Optional, Identify the block of statement that are in labelled block.

JavaScript label with break statement

Example

<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

JavaScript label with continue statement

Example

<script>
for(var i = 1; i < 5; i++){
    inner:
    for (var j = 0; j < 5; j++){
        if (j == 2){
            document.writeln("skipped");
            continue inner;
        }
        document.writeln("i : " + i + ", j :" + j);
    }
    document.writeln();
}
</script>

Run it...   »

Example Result

JavaScript label with break statement and continue statement

Example

<script>
outer:
for(var i = 1; i <= 3; i++){
    inner:
    for (var j = 0; j <= 5; j++){
        if (j == 2){
            document.writeln("skipped");
            continue inner;
        } else if(j == 4){
            document.writeln("terminated");
            break inner;
        }
        document.writeln("i : " + i + ", j :" + j);
    }
    document.writeln();
}
</script>

Run it...   »

Example Result