Search code examples
javascriptbreaklabeled-statements

Nested Javascript for loops with break and label statements


I'm kinda new to Javascript and currently going over the book Professional Javascript for Web Developers and I came across this code which uses a break statement to exit the current loop and jump to a label named outermost.

Now I understand what break and labels do but I can't wrap my head around why the value ends up being 55 at the end?

Ok so the for loop with var i will loop 4 times then at 5 it breaks out to label:outermost and same with j so the first iteration i = 4 and j = 4 and num = 2. I guess this part confuses me.. at what point does the code stop. My first instinct if I were to code this from scratch is to have an outside variable and set the condition on that. But with the below code I don't get where the control structure lies and the final value. Appreciate any help or to be pointed in the right direction, thanks.

var num = 0;

outermost:

for (var i=0; i < 10; i++) {
    for (var j=0; j < 10; j++) {
        if (i == 5 && j == 5) {
            break outermost;
        }
        num++;
    }
}
alert(num);

Solution

  • This nested loop is emulating an odometer. i is the 10's digit, j is the 1's digit. Every time the 1's digit changes, num is incremented; at the start of each iteration, num contains the odometer's value.

    The loop stops when both i and j are 5. At that point, the odometer would read 55, and that's what is in num.