Javascript - Use break statement with label


Both the break and continue statements can use labeled statements to return to a particular location.

This is typically used for nested loops:


var num = 0;

outermost:/* w  w  w. ja  va2 s . c o m*/
for (var i=0; i < 10; i++) {
     for (var j=0; j < 10; j++) {
        if (i == 5 && j == 5) {
            break outermost;

console.log(num);    //55


In this example, the outermost label indicates the first for statement.

Each loop normally executes 10 times, meaning that the num++ statement is normally executed 100 times.

The break statement here is given one argument: the label to break to.

The break statement will break out of the outer for statement.

num ends up with a value of 55, because execution is halted when both i and j are equal to 5.

Related Topic