17.8 Multiple Repetitions of Program Statements via Loops
Loops are very suitable if you want to repeat certain statements multiple times. JavaScript supports several types of loops, which I’ll briefly describe in the following sections.
17.8.1 Increment and Decrement Operators
An increment or decrement increases or decreases the value of a variable by 1. These two operators are predominantly used with loops. The operators are written in JavaScript as follows:
Operator |
Meaning |
---|---|
|
Increment operator; variable is incremented by 1. |
|
Decrement operator; variable is decremented by 1. |
Table 17.6 Increment and Decrement Operators
There are two possibilities for the use of these two operators: postfix notation and prefix notation.
Usage |
Meaning |
---|---|
|
Postfix notation; increments the value of |
|
Prefix notation; increments the value of |
|
Postfix notation; reduces the value of |
|
Prefix notation; reduces the value of |
Table 17.7 Postfix and Prefix Notations
Here’s a simple example to demonstrate the increment operator (++)
in more detail. The same applies to the decrement operator (--
).
let iVal = 1;
console.log("iVal = " + iVal); // Output: iVal = 1
iVal++;
console.log("iVal = " + iVal); // Output: iVal = 2
console.log("iVal = " + iVal++); // Output: iVal = 2
console.log("iVal = " + iVal); // Output: iVal = 3
console.log("iVal = " + ++iVal); // Output: iVal = 4
The first time the increment operator is used, the old value is still passed to the current expression. Because the increment is standing alone here, this is also the current expression. The next line of output, on the other hand, is the next expression, which is why the value of iVal
is 2
in this case. You’ll understand it better if you run iVal++
inside console.log()
in the next line. Here the output is still 2
because the increment is executed within the current expression. The current expression ends at the semicolon where the late increment (and, if used, decrement) takes effect. The next expression in the next line has the expected value 3
. If you want to increment the value of a variable immediately within an expression, you must use the prefix notation instead of the postfix notation, as I did in the last line with ++iVal
.
17.8.2 The Header-Controlled “for” Loop
You’ll probably want to use the flexible for
loop most often. The syntax for this loop looks as follows:
for (initialization; condition; increment/decrement) {
// statement block that will be executed
}
Initialization
is executed only once when the loop is started and is usually used to set a count variable for the loop. Condition
, on the other hand, usually represents the condition for the statements in the statement block of the loop to be executed. As long as the condition in Condition
equals true
, the loop will be executed again. If false
, the loop terminates, and program execution continues after the statement block of the for
loop. As a condition, it’s often checked whether the count variable corresponds to a certain value. Increment/Decrement
, on the other hand, is always executed when the statements in the statement block have been executed. Most of the time, you want to change the count variable of the loop here.
A simple use of the for
loop could look as follows:
for (let i = 0; i < 3; i++) {
console.log(i + 1 + "-th loop pass");
}
For demonstration purposes, the loop was output to the console. In the process, the statement was executed three times in the loop. The count variable i
was first set to 0, the condition i<3
was checked and then the statement block after it was executed. The output in the JavaScript console shows how many times the loop has been executed. Next, the loop variable is incremented by 1 with i++
, and the condition i<3
is checked again, which (i=1
) is still true
. The process gets repeated until the value of i
equals 3
and thus the condition i < 3
returns false
.
The output of the example in the console looks as follows:
1st loop pass
2nd loop pass
3rd loop pass
All Three Expressions in the “for” Loop Are Optional
All three expressions in the for
loop are optional and can be omitted. In any case, you must use the two semicolons in the for
loop. Theoretically, for(;;)
would be a valid for
loop. Note, however, that if you omit the second expression, you’ll create an infinite loop, which could crash the browser sooner or later. If you use an infinite loop, you should use a break
inside this loop. Such a break
can be used to jump out of the loop.
17.8.3 The Header-Controlled “while” Loop
The while
loop is a header-driven loop and is executed as long as the condition in while
returns true
. Here’s the syntax:
while (condition) {
// statement block that will be executed
}
In practice, you can loop
through a block of statements using the while
loop as follows:
let i = 0; // Initialize counter variable
while (i < 3) { // Check condition
console.log(i + 1 + "-th loop pass");
i++; // Increment count variable
}
You know the example from the for
loop, except that here you’ve initialized the count variable before the loop pass, and you increment the loop variable itself at the end of the statement block. The danger in this case, in contrast to the example with the for
loop, might be that you forget to increment the variable for the loop condition. In practice, a while(condition)
corresponds to a for(;condition;)
.
17.8.4 The Footer-Controlled “do-while” Loop
In the do
-while
loop, as opposed to the while
loop, the condition isn’t checked until the end, when the statement block has been executed. Thus, in the do
-while
loop, the statement block of the loop is executed at least once before the condition gets checked. Here’s the syntax for the do
-while
loop:
do{
// statement block that will be executed
} while (condition);
Here’s an example in which a loop pass occurs three times:
let i = 0;
do {
console.log(i + 1 + "-th loop pass");
i++;
} while (i < 3);
17.8.5 Ending the Statement Block Using “break”
A statement that can be very useful within a loop is the break
statement. If you use a simple break
inside a statement block of the loop, it will jump out of the loop execution, and the script will continue after the loop. Here’s a short code snippet:
let i = 0;
while (i < 10) {
console.log(i + 1 + "-th loop pass");
i++;
if (i === 5) {
console.log("End loop with break");
break;
}
}
As a matter of fact, this loop should be run 10 times according to the condition in while
. However, this loop runs only 5 times because then the if
condition i==5
returns true
so that the break
statement ensures that the loop terminates prematurely.
17.8.6 Jumping to the Start of the Loop via “continue”
With continue
, you end a loop pass and jump back to the beginning of the loop. This is useful if you don’t want to execute the further loop pass due to a condition. Let’s take a look at a simple example:
let i = 0;
while (i < 10) {
i++;
if (i % 2 === 1) {
continue;
}
console.log("Value divisible by 2: " + i);
}
In the example, a loop is incremented from 1 to 10 and passed through. Each loop pass checks whether the value of i % 2
(i modulo) results in a remainder. If the condition is true
, continue
jumps back to the beginning of the loop. If the condition is false
, it’s a number divisible by two or an even value, and the number is output.