-2

I'm reading an article on the MDN website about loops and iteration. I'm trying to understand why we are getting the 1, 3, 7, 12 as a result from the following?:

var i = 0;
var n = 0;
while (i < 5) {
 i++;
  if (i == 3) {
  continue;
  }
 n += i;
}

Wouldn't the continue statement cause it to skip 3?

theAussieGuy
  • 157
  • 1
  • 2
  • 11

3 Answers3

2

What continue does is immediately jump to the top of your loop. Essentially, it ignores everything following it and moves on to the next iteration.

To give a simpler example, here's how to print only the even numbers in a range:

for (var i = 0; i < 10; i++) {
  // If i isn't even, skip to the next iteration
  if (i % 2 !== 0) {
    continue;
  }
  console.log(i);
}

Because of this, you are not adding 3 to your running sum. Instead, you essentially get:

var i = 0;
var n = 0;
i++; // 1
n += i; // 1

i++; // 2
n += i; // 3

i++; // 3
// skip 3

i++; // 4
n += i; // 7

i++; // 5
n += i; // 12
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

Yes. When i equals 3, the loop is skipped. The Focus is rather on n, which has the values 1, 3, 7, 12

jaap-de-boer
  • 137
  • 1
  • 1
  • 8
0

I've overlooked the assignment operator in this example (+=).

As we loop it progresses as follows:

After the first loop, x=1 and y=1, we progress and add another 1 to x which now = 2. Due to the assignment operator (n += x) we add two(x) to one(y).

At this stage we loop again and the operation realises that x has become three, so it 'skips' that assignment operator and continues.

theAussieGuy
  • 157
  • 1
  • 2
  • 11