Core JavaScript

Intermediate JavaScript

JavaScript Reference



JavaScript label break continue example


JavaScript label mainly use with break and/or continue statement. 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.

Example (label with break statement) :

<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 :


Example (label with continue statement) :

<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 :


Example (label with break statement and continue statement) :

<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 :