Loops, how does this one work?

for (let outer = 0; outer < 2; outer += 1) {
for (let inner = 0; inner < 3; inner += 1) {
console.log(${outer}-${inner});
}
}

/*
Output:
0-0
0-1
0-2
1-0
1-1
1-2
*/

why does the first iteration of the outer loop begin with 0 instead of 1? And why does the inner loop go from 0 to 2 and back again to 0 and so forth?

Why would you expect the outer loop to start with one?

you nested the loop, so for each iteration of the outer loop, the inter loop makes all its iterations (each time)

doesn’t it say: let outer = 0 (so it begins iterating at index 0)
outer < 2 (it will stop (or check the value) if the value is still less than 2
outer += 1 (will add 1 each time the loop runs)??

at the end of the iteration, if you want to increment before you can ++i.

1 Like