Loops in JavaScript
Loops are fundamental control flow structures that allow you to repeatedly execute a block of code as long as a specified condition is met. JavaScript provides a variety of loop constructs, each optimized for specific use cases ranging from iterating over arrays and objects to handling asynchronous operations.
1. The Standard for Loop
The classic for loop is ideal when you know exactly how many times you want to iterate.
for (let i = 0; i < 5; i++) {
console.log(i); // Outputs 0, 1, 2, 3, 4
}
- Initialization (
let i = 0): Executed once before the loop begins. - Condition (
i < 5): Evaluated before each iteration. If true, the loop continues. - Final Expression (
i++): Executed at the end of each iteration.
2. while and do...while Loops
while Loop
Executes as long as the condition evaluates to true. Best used when the number of iterations is unknown and depends on external factors.
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
do...while Loop
Similar to the while loop, but the block of code is guaranteed to execute at least once, because the condition is evaluated after the iteration.
let count = 0;
do {
console.log("Runs at least once", count);
count++;
} while (count < 0);
3. Iterating Over Objects: for...in
The for...in loop iterates over all enumerable properties of an object (including inherited properties from its prototype chain).
const user = { name: "Alice", role: "Admin" };
for (const key in user) {
if (user.hasOwnProperty(key)) {
console.log(`${key}: ${user[key]}`);
}
}
Note: It is generally not recommended to use for...in for arrays, as it iterates over property keys (which are strings) and can include inherited properties.
4. Iterating Over Iterables: for...of
Introduced in ES6, for...of is the modern way to iterate over iterable objects like Arrays, Strings, Maps, and Sets. It provides the values directly.
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
5. Array Iteration Methods
Modern JavaScript relies heavily on functional array methods instead of traditional loops. These are declarative and often easier to read.
forEach(): Executes a provided function once for each array element.[1, 2, 3].forEach(num => console.log(num * 2));map(): Creates a new array populated with the results of calling a provided function.filter(): Creates a new array with all elements that pass the test implemented by the provided function.reduce(): Executes a reducer function on each element, resulting in a single output value.
6. Loop Control: break and continue
break: Immediately exits the loop entirely.continue: Skips the rest of the current iteration and jumps to the next iteration.
for (let i = 0; i < 10; i++) {
if (i === 3) continue; // Skips 3
if (i === 7) break; // Stops at 7
console.log(i);
}
7. Best Practices
- Prefer
constinfor...ofandfor...inloops to prevent accidental reassignment. - Avoid deep nesting of loops, which degrades performance to or worse.
- Use declarative methods (
map,filter,reduce) overforloops when transforming data.