How does this specific nested for loop work in vanilla JavaScript?

1.5k Views Asked by At

I got a quiz question in my Full Stack Web Development online course that states the following:

let sum = 0;
for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 2; j++) {
        sum = sum + i + j;
        continue;
    }
}
console.log(sum);

Now, the correct answer to the question is 25 according to the answer of the quiz, but I have no idea how it gets to 25? The closest I get when writing it out on paper to try and visualize it, is either 15 / 16.

Could someone please write a visualization that would make it clearer for me on how this nested loop gets to 25?

Thanks in advance.

5

There are 5 best solutions below

2
On BEST ANSWER

Add a console after second for, you should see the visualization

let sum = 0;
for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 2; j++) {
        console.log(`sum=${sum} i=${i} j=${j}`)
        sum = sum + i + j;
        continue;
    }
}
console.log(sum);

//output
// sum=0 i=0 j=0
// sum=0 i=0 j=1 
// sum=1 i=1 j=0 
// sum=2 i=1 j=1 
// sum=4 i=2 j=0 
// sum=6 i=2 j=1 
// sum=9 i=3 j=0 
// sum=12 i=3 j=1
// sum=16 i=4 j=0
// sum=20 i=4 j=1
// 25
2
On

This loop is calculated like this.

(1+2+3+4) * 2 = 20 (0+1) * 5 = 5

So sum = 20 + 5 = 25

1
On

Here are all the iterations of the loops, and the value of sum after each.

i = 0 j = 0 sum = 0 + 0 + 0 = 0
i = 0 j = 1 sum = 0 + 0 + 1 = 1
i = 1 j = 0 sum = 1 + 1 + 0 = 2
i = 1 j = 1 sum = 2 + 1 + 1 = 4
i = 2 j = 0 sum = 4 + 2 + 0 = 6
i = 2 j = 1 sum = 6 + 2 + 1 = 9
i = 3 j = 0 sum = 9 + 3 + 0 = 12
i = 3 j = 1 sum = 12 + 3 + 1 = 16
i = 4 j = 0 sum = 16 + 4 + 0 = 20
i = 4 j = 1 sum = 20 + 4 + 1 = 25
2
On

Perhaps this will give you more visualization of on what's going on:

let sum = 0;
for (let i = 0; i < 5; i++) {
console.log("loop start");
console.log("i", i);
    for (let j = 0; j < 2; j++) {
console.log("sum", sum);
console.log("j", j);
        sum = sum + i + j;
        continue;
    }
console.log("loop end");
}
console.log(sum);

4
On

The left side would be the values of i and j:

0 // i
0 1 // j  // sum = 0 | sum = 1 + (0) <-- () is previous value of sum
        
1
0 1       // sum = 1 + (1) | sum = 2 + (2)
     
2
0 1       // sum = 2 + (4) | sum = 3 + (6)

3
0 1       // sum = 3 + (9) | sum = 4 + (12)

4
0 1       // sum = 4 + (16)| sum = 5 + (20)