I was trying to code along a tutorial on using the “continue” statement in a while loop. In the tutorial, the code was written as shown below and it worked fine.
JavaScript
x
13
13
1
var x = 1;
2
document.write("Entering loop");
3
4
while (x < 20) {
5
x++;
6
if (x == 5) {
7
continue;
8
}
9
10
document.write(x + "<br />");
11
}
12
document.write("Exiting the loop");
13
but I tried it differently and it resulted to an infinite loop when I put the increment statement after the “if” block as shown below.
JavaScript
1
15
15
1
2
var x = 1;
3
document.write("Entering loop");
4
5
while (x < 20) {
6
7
if (x == 5) {
8
continue;
9
}
10
x++;
11
document.write(x + "<br />");
12
}
13
document.write("Exiting the loop");
14
15
I have tried to wrap my head around it but I have not been able to figure it out. Why is this so?
Advertisement
Answer
The
JavaScript
1
4
1
if (x == 5) {
2
continue;
3
}
4
alone means that x will never change once it reaches 5. Putting x++ before that means that x will change.
With x++ after, the loop will continue
every time, infinitely.