Loops in JavaScript allow you to execute a block of code multiple times, which is essential for tasks like iterating over arrays, objects, or performing repeated calculations.
1. The for Loop
The for loop is commonly used when the number of iterations is known:
for (let i = 0; i < 5; i++) {
console.log("Iteration:", i);
}
iis the loop counter.- The loop continues while the condition (
i < 5) is true. i++increments the counter after each iteration.
2. The while Loop
The while loop runs as long as a condition is true:
let count = 0;
while (count < 5) {
console.log("Count:", count);
count++;
}
- Use
whilewhen the number of iterations is not known in advance.
3. The do...while Loop
Executes the block at least once, then checks the condition:
let num = 0;
do {
console.log("Number:", num);
num++;
} while (num < 5);
- Useful when you want the code to run at least one time regardless of the condition.
4. The for...of Loop
Simpler way to loop through arrays:
let fruits = ["apple", "banana", "mango"];
for (let fruit of fruits) {
console.log(fruit);
}
- Iterates over values directly, not indexes.
5. The for...in Loop
Used to iterate over object properties:
let person = {name: "Alice", age: 25, city: "New York"};
for (let key in person) {
console.log(key + ": " + person[key]);
}
- Iterates over keys, not values directly.
6. Break and Continue
Control loop execution:
for (let i = 0; i < 10; i++) {
if (i === 5) break; // Stops loop
if (i % 2 === 0) continue; // Skips even numbers
console.log(i); // 1, 3
}
7. Practical Tips
- Loops are essential for processing arrays and objects.
- Avoid infinite loops by ensuring the condition eventually becomes false.
- Use
for...offor arrays andfor...infor objects for cleaner code.
Mastering loops is key to automating repetitive tasks and processing data efficiently in JavaScript.
Citations: