I'm trying to understand this code step by step. Plz help


#1

I am trying to understand this code below step by step.

var i = 0;
var j = 8;

checkiandj: while (i < 4) {
  console.log('i: ' + i);
  i += 1;

  checkj: while (j > 4) {
    console.log('j: ' + j);
    j -= 1;

    if ((j % 2) == 0)
      continue checkj;
    console.log(j + ' is odd.');
  }
  console.log('i = ' + i);
  console.log('j = ' + j);
}

I did not understand this part:

 if ((j % 2) == 0)
      continue checkj;
    console.log(j + ' is odd.');

I got it that if j is even, continue will be executed and it will restart the loop at the next iteration.

If j is odd, it will print out that j is odd.

But again checkj loop will be executed and all the values of j will be printed out before the values of i??

I was going through MDN to go deeper in JavaScript and the code above is given as an example of the continue statement.


Plz help.


#2

If the keyword continue is encountered, the program continues (goes back to) at the top of the checkj statement. Each time continue is encountered, checkj reiterates until its condition returns false. Does that make sense? Let me know if that got your head around it.


#3

So ur saying that it doesn't matter whether j is even or odd? The continue statement will keep looping through checkj?

I thought that if j is even, it will reiterate checkj but if j is odd it will print out j is odd and continue with checkiandj.

I know what continue statements are but I'm having problems in finding out how it is working in this code.


#4

So I think this code is meant to check if J is even and if it is go back up to checkj. However this code is wrong and will only work if it has braces. Like this:

if ((j % 2) == 0) {
continue checkj; }

#5

That's exactly what I was thinking! I also thought that there is something wrong with this code (although I thought that it's highly unlikely that the MDN will have any problem in any of it's code) and it should have brackets like u wrote in the code above.

So it means that the code should be:

var i = 0;
var j = 8;

checkiandj: while (i < 4) {
  console.log('i: ' + i);
  i += 1;

  checkj: while (j > 4) {
    console.log('j: ' + j);
    j -= 1;

    if ((j % 2) == 0) {
    continue checkj; 
  } else {
    console.log(j + ' is odd.');
  }

  }
  console.log('i = ' + i);
  console.log('j = ' + j);
}

Means that if j is odd, it will print out j is odd and continue with checkiandj right?