Iteration involves the repetition of a block of code several times until a desired task is complete.
In JavaScript, there are three main tools that can be used for iterations:
The for loop
is the best tool to use when the number of repetitions is known. If an operation needs to be performed on every element
in an array of length N, it becomes clear that N operations are needed and the for loop
can be used to accomplish this
const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
arr[i] += 10;
}
When the number of repetitions needed is unknown, then the while loop
is the recommended tool. To find the number of times a number can be divided by 2, the while loop
is a good choice because the number of repetitions is unknown in this case
let n = 10,
r = 0;
while (n % 2 === 0) {
n /= 2;
r++;
}
The do while
loop can be used when the operation to be repeated must be performed at least once.
let n = 10;
do {
console.log(n);
n--;
} while (n > 0);