Loops are a core feature in JavaScript that allow you to execute a block of code multiple times efficiently. Understanding how to use loops effectively can save time, reduce code repetition, and make your programs more readable. This guide explores different types of loops and best practices.
1. The for Loop
The for loop is ideal when you know in advance how many times you want to iterate:
for (let i = 0; i < 5; i++) {
console.log('Iteration:', i);
}
- Initialization:
let i = 0runs once before the loop starts. - Condition:
i < 5is checked before each iteration. - Increment/Decrement:
i++updates the counter after each iteration.
2. The while Loop
The while loop continues as long as a condition is true:
let i = 0;
while (i < 5) {
console.log('Iteration:', i);
i++;
}
- Useful when the number of iterations is unknown beforehand.
- Make sure the condition eventually becomes false to avoid infinite loops.
3. The do…while Loop
The do...while loop guarantees at least one execution before checking the condition:
let i = 0;
do {
console.log('Iteration:', i);
i++;
} while (i < 5);
- Good for situations where code should run once even if the condition is false.
4. Iterating Over Arrays
a. for Loop
const fruits = ['Apple', 'Banana', 'Orange'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
b. for…of Loop
Simpler syntax for iterating over array elements:
for (const fruit of fruits) {
console.log(fruit);
}
for...ofis cleaner and avoids manual index management.
c. forEach() Method
forEach() executes a callback for each array element:
fruits.forEach((fruit, index) => {
console.log(index, fruit);
});
- Perfect for array iteration when you don’t need a return value.
5. Iterating Over Objects
Use for...in to loop over object properties:
const person = { name: 'John', age: 30, city: 'New York' };
for (const key in person) {
console.log(key, person[key]);
}
for...initerates over enumerable property keys.
6. Nested Loops
Loops can be nested for multidimensional data:
const matrix = [
[1, 2],
[3, 4]
];
for (const row of matrix) {
for (const value of row) {
console.log(value);
}
}
- Useful for grids, tables, and complex data structures.
7. Break and Continue
- break: Exits the loop immediately.
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i); // 0, 1, 2
}
- continue: Skips the current iteration.
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i); // 0, 1, 3, 4
}
- Use these statements carefully for better loop control.
8. Best Practices
- Choose the appropriate loop type for readability and performance.
- Avoid modifying the array or object you are iterating over if possible.
- Use
for...ofandforEach()for arrays to write cleaner code. - Always ensure loops have a condition that eventually stops.
9. Wrapping Up
Loops are essential for automating repetitive tasks and processing collections of data in JavaScript. By mastering for, while, do...while, for...of, and forEach(), you can write efficient and maintainable code for a wide range of applications.
Next Step: Combine loops with conditional statements and array methods like map(), filter(), and reduce() to handle complex data operations effectively.
