1

my question is about the following code:

let iterations = 0; 
    top: for (let i = 0; i < 5; i++) { 
            for (let j = 0; j < 5; j++) { 
                iterations++; 
                if (i === 2 && j === 2) { 
                    break top; 
                } 
            } 
        } 
    console.log(iterations); // OUTPUTS: 13

I am not sure if this is an object, a function or what (I am talking about the top:) and also I don't know how the OUTPUT is 13, I know that It has 2 iterations, but my question is, does the condition inside the loop ever gets true? or not? and why?

UPDATE: This is a label... Sorry for my ignorance.

Thank you and blessings.

2 Answers2

0

The top: is an name for the outer loop which is used in the inner break to define which loop to break.

And to know how it works add another output:

let iterations = 0; 
top: for (let i = 0; i < 5; i++) { 
        for (let j = 0; j < 5; j++) { 
            console.log(i, j)
            iterations++; 
            if (i === 2 && j === 2) { 
                break top; 
             } 
        } 
    } 
console.log(iterations);

Now you will get:

0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2

And thats exactly 13 iterations. The inner loop will two times go to its maximum till the outer loop reaches 2.

Alinex
  • 914
  • 8
  • 18
  • So if I modify my code for adding the "top:" right before the second for it will continue looping in the first loop once it reaches to i == 2 and j == 2 in the second... Right? – Reynald Ramirez Oct 23 '20 at 21:43
  • If you only want to break out of the inner loop you won't need the "top" label. Only write `break`. But if this is what you want? Try it out. It will do the same as before, then skipping i==2 j==3 ... and go on with i==3. – Alinex Oct 25 '20 at 07:15
0

It is neither it is a label. From the MDN Docs:

The labeled statement can be used with break or continue statements. It is prefixing a statement with an identifier which you can refer to.

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40