October 3, 2024
The JavaScript continue statement
In JavaScript, is a while loop always exactly equivalent to a for loop?
The short answer, where M150 is concerned, is yes. However, in a wider context this is not always the case.
Equivalent while and for loops take the form
initialize;
while(test)
{
statement;
increment;
}
for(initialize;test;increment)
{
statement;
}
One can write for example
var i = 0;
var total;
while(i<5)
{
total = total + i;
i = i +1;
document.write(total +'<br>');
}
Or one can use a for loop
var total;
for (var i = 0; i<5; i = i+1)
{
total = total + i;
document.write(total +'<br>');
}
Both the test condition and behaviour are identical. In both cases the counter is initialised just once before the loop starts. The test condition is checked before each loop and if it returns true, the loop body is executed. Then the counter is incremented. These two loop constructs are equivalent.
Now let's look at the use of a continue statement, which is not taught on
M150.
When the continue statement is executed, which in the following
example will be the case if the value of i is 3,
the current loop is stopped and the test condition is once again evaluated.
The counter must be incremented at the start of the loop, otherwise an infinite
loop will result as i will never have a value greater than 3.
The continue statement causes the statements below it to be skipped.
The loop does not stop and its control remains with the test condition.
var i = 0;
var total = 0;
while (i < 5)
{
i = i +1;
if (i == 3)
continue;
total = total + i;
document.write(total +'<br>');
}
The browser output reads
1
3
7
12
Now run this and note that in a for loop, when the continue
statement is executed, the increment statement
i = i+1
is immediately executed before the test condition i < 5
is evaluated. If true is returned, the next loop begins, else
it shuts down.
var total = 0;
for (var i = 0; i < 5; i = i +1 )
{
if (i == 3)
continue;
total = total + i;
document.write(total +'<br>');
}
The browser output now reads
0
1
3
7
The initial loop counter value, test condition and increments are identical, but the resulting behaviour is different.
To match the output from the while loop, the test condition in the for loop must be rewritten.
var total = 0;
for (var i = 1; i < 6; i = i+1)
{
if (i == 3)
continue;
total = total + i;
document.write(total +'<br>');
}
In conclusion, when a loop body includes a continue statement, a while loop is no longer exactly equivalent to a for loop.
Previous page « Event driven programming
⇑ Up to top of page