Iteration in JavaScript
JavaScript supports two types of while loopsRepetition while a condition is true. and two types of for loopsRepetition a fixed number of times.. Like branching, these features do not differ significantly from those found in other programming languages.
In all the examples below, the loop bodies can have any number of statements.
Iteration using while
JavaScript supports not only a while loop but also a do/while loop. The latter is used if you wish to complete an iterationThe process of repeating, or one repetition in that process. before first testing the condition. Here is the syntaxThe rules for expression. for a while loop:
while (condition) {
statement1;
statement2;
}
Here is the syntax for a do/while loop:
do {
statement1;
statement2;
} while (condition)
Iteration using for
There are two types of for loops, for and for in. We will consider only the first type in this lesson. In a for loop, three expressions are provided, where the first is initialization, the second is a condition, and the third is an update.
for (counter = 0; counter < 5; counter++) {
statement;
statement;
}
Another example of an update is counter = counter + 5
, or any other way of changing the value of counter
.
In addition, a break
statement in a for loopRepetition a fixed number of times. provides an exit out of all iterations, and a continue
statement provides an exit out of the current iteration only.