user269630
user269630

Reputation: 3

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);

Upvotes: 0

Views: 166

Answers (2)

Fabricator
Fabricator

Reputation: 12772

When i was 0 to 4, the innermost loop is executed 50 times. When i = 5, the innermost loop is executed just 5 times until it reached i==5 && j==5 and jumped out. So it's total of 55 times.

Upvotes: 0

Barmar
Barmar

Reputation: 781058

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.

Upvotes: 0

Related Questions