Loops & Iteration
JavaScript supports the standard loop constructs you have seen in other programming languages:
let counter = 0;
while (counter < 10) {
console.log(counter);
counter++;
}
In a do-while loop, the body runs once first. Then, if the condition holds, the program goes back to the top of the block.
let counter = 10;
do {
console.log(counter);
counter++;
} while (counter < 10);
A loop is counter-controlled when we know exactly how many iterations we need, for example when we go over the elements of an array. For those loops, the for loop gives us a more compact syntax:
for (let counter = 0; counter < 10; counter++) {
console.log(counter);
}
You can include multiple variables and update expressions:
const arr = [10, 20, 30, 40, 50];
for (let i = 0, j = arr.length - 1; i < j; i++, j--) {
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
console.log(arr);
A loop is event-controlled when the number of iterations is unknown before runtime, for example when we read data from a file and do not know how many lines or how many values are there. The while and do-while loops are best for those.
Altering Loop Flow
There are two statements that can alter the flow of loops: break and continue.
The break statement exits out of a loop:
const arr = [10, 20, 30, 40, 50];
const target = 40;
let index = -1;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
index = i;
break; // stop early!
}
}
console.log(index); // 3
The continue statement will skip to the next iteration:
const arr = [10, , 30, , 50];
let count = 0;
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === undefined) {
continue; // ignore missing data!
}
count++;
sum += arr[i];
}
const avg = count === 0 ? 0 : sum / count;
console.log(avg);
Enhanced Loops
There are two kinds of enhanced loops in JavaScript: for..of and for..in. The difference is that for..of iterates over values, and for..in iterates over keys (property names). These loops work with iterable and enumerable objects, which are covered in more detail in the chapter on iterables and enumerables.
The for..of loops are used for looping through iterable objects such as arrays.
let arr = [10, 20, 30];
for (let item of arr) {
console.log(item);
}
It also works with strings:
const greeting = "Hello!";
for (const ch of greeting) {
console.log(ch);
}
The for..in loop allows you to iterate over keys of enumerable object properties, including inherited ones.
const user = {
firstName: "Ali",
lastName: "Madooei",
};
for (const key in user) {
console.log(key, user[key]);
}
It works with arrays too, but iterates over the indices:
const arr = [10, 11, 12];
for (const key in arr) {
// console.log(key);
console.log(arr[key]);
}
Similar to arrays, for..in also works with strings and iterates over the indices (character positions):
const greeting = "Hello!";
for (const key in greeting) {
// console.log(key);
console.log(greeting[key]);
}