Loops are an essential part of JavaScript, enabling you to execute a block of code multiple times. Understanding the different types of loops and when to use them will make your coding more efficient and your applications more powerful. This chapter covers for, while, do...while, for...in, and for...of loops.

for Loops

The for loop is a fundamental loop structure in JavaScript. It's used when you know beforehand how many times you need to execute a statement or a block of statements.

Syntax:

for (initialization; condition; increment) {
  // code to be executed
}

Example:

for (let i = 0; i < 5; i++) {
  console.log(i); // Output: 0, 1, 2, 3, 4
}

In this example, the loop starts with i set to 0, continues to run as long as i is less than 5, and increments i by 1 each iteration. The code inside the loop (console.log(i)) executes five times, logging numbers 0 to 4.

while Loops

The while loop repeats a block of code as long as a specified condition evaluates to true. This loop is useful when the number of iterations is not known in advance.

Syntax:

while (condition) {
  // code to be executed
}

Example:

let i = 0;
while (i < 5) {
  console.log(i); // Output: 0, 1, 2, 3, 4
  i++;
}

In this example, the loop starts with i set to 0 and continues to execute as long as i is less than 5. After each iteration, i is incremented by 1.

do...while Loops

The do...while loop is similar to the while loop but guarantees that the block of code will execute at least once before the condition is evaluated.

Syntax: