JavaScript Loops
Loops are fundamental control flow structures in programming that allow you to execute a block of code repeatedly. This is incredibly useful for performing repetitive tasks, processing collections of data, and automating processes.
Why Use Loops?
Imagine you need to display the numbers from 1 to 10. Without loops, you would write 10 separate console.log()
statements:
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
console.log(6);
console.log(7);
console.log(8);
console.log(9);
console.log(10);
This is tedious, error-prone, and not scalable. Loops provide a much more elegant solution.
Common Types of Loops in JavaScript
1. for
Loop
The for
loop is ideal when you know exactly how many times you want to iterate. It consists of three parts:
- Initialization: Executed once before the loop starts (e.g., setting a counter variable).
- Condition: Evaluated before each iteration. If true, the loop continues; otherwise, it stops.
- Increment/Decrement: Executed after each iteration (e.g., increasing or decreasing the counter).
for (let i = 0; i < 5; i++) {
console.log("Iteration number: " + i);
}
Iteration number: 0
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
2. while
Loop
The while
loop executes a block of code as long as a specified condition is true. It's useful when the number of iterations is not known in advance.
let count = 0;
while (count < 3) {
console.log("Count is: " + count);
count++; // Important: update the condition to avoid an infinite loop
}
Count is: 0
Count is: 1
Count is: 2
3. do...while
Loop
The do...while
loop is similar to the while
loop, but it guarantees that the code block will be executed at least once, regardless of whether the condition is initially true. The condition is checked after the loop body has run.
let j = 5;
do {
console.log("Executing once, j is: " + j);
j++;
} while (j < 5);
Executing once, j is: 5
4. for...in
Loop
The for...in
loop is used to iterate over the enumerable properties of an object (keys).
const person = { name: "Alice", age: 30, city: "New York" };
for (const key in person) {
console.log(key + ": " + person[key]);
}
name: Alice
age: 30
city: New York
5. for...of
Loop
The for...of
loop is used to iterate over iterable objects like Arrays, Strings, Maps, Sets, etc. It iterates over the values of the iterable.
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log("Color: " + color);
}
Color: red
Color: green
Color: blue
Controlling Loop Execution
You can use two keywords to control the flow within loops:
break
: Terminates the loop immediately.continue
: Skips the rest of the current iteration and proceeds to the next one.
break
Example:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Stop the loop when i reaches 5
}
console.log("Before break: " + i);
}
Before break: 0
Before break: 1
Before break: 2
Before break: 3
Before break: 4
continue
Example:
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // Skip the rest of this iteration when i is 2
}
console.log("After continue: " + i);
}
After continue: 0
After continue: 1
After continue: 3
After continue: 4
Choosing the Right Loop
The best loop to use depends on your specific needs:
- Use
for
when you know the number of iterations. - Use
while
when the loop should continue as long as a condition is met, and the number of iterations is not fixed. - Use
do...while
when you need to execute the loop body at least once. - Use
for...in
to iterate over object properties (keys). - Use
for...of
to iterate over the values of iterable objects.