Control Flow: Loops (for, while, do...while)
Learn different types of loops to repeat code blocks, including for loops, while loops, and do...while loops.
JavaScript Loops: Essentials
Control Flow: Loops
Loops are fundamental control flow structures in programming that allow you to execute a block of code repeatedly. They are essential for automating repetitive tasks and processing data efficiently. JavaScript provides several types of loops, each with its own syntax and use cases.
Different Types of Loops
for
Loop
The for
loop is a powerful and versatile loop that's ideal when you know how many times you need to iterate. It consists of three parts, separated by semicolons:
- Initialization: Executed once at the beginning of the loop. Typically used to declare and initialize a counter variable.
- Condition: Evaluated before each iteration. The loop continues as long as the condition is true.
- Increment/Decrement: Executed after each iteration. Typically used to update the counter variable.
for (let i = 0; i < 5; i++) {
console.log("Iteration: " + i);
}
Explanation: In this example, i
is initialized to 0. The loop continues as long as i
is less than 5. After each iteration, i
is incremented by 1. The output will be:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
The for
loop can also iterate over arrays:
const myArray = ["apple", "banana", "cherry"];
for (let i = 0; i < myArray.length; i++) {
console.log("Element at index " + i + ": " + myArray[i]);
}
while
Loop
The while
loop executes a block of code as long as a specified condition is true. The condition is checked before each iteration. It's used when the number of iterations isn't known in advance, and depends on a certain condition being met.
let count = 0;
while (count < 3) {
console.log("Count: " + count);
count++;
}
Explanation: The loop continues as long as count
is less than 3. Inside the loop, count
is printed and then incremented. The output will be:
Count: 0
Count: 1
Count: 2
do...while
Loop
The do...while
loop is similar to the while
loop, but it guarantees that the code block is executed at least once. The condition is checked after each iteration.
let i = 0;
do {
console.log("Value of i: " + i);
i++;
} while (i < 2);
Explanation: Even if the condition i < 2
was initially false (if i
started at 2, for example), the code inside the do
block would still execute once. The output will be:
Value of i: 0
Value of i: 1