JavaScript Looping Techniques
This article is a complementary resource to the Learn JavaScript Basics course.
This article is a complementary resource to the Learn JavaScript Basics course.
JavaScript Looping Techniques
Loops are essential in JavaScript for automating repetitive tasks. But the real magic happens when you use them creatively and efficiently.
This blog skips the theory and dives straight into practical tips, tricks, and real-world applications of loops.
You use the for loop when the number of iterations is known or predictable. For example,
for (let i = 0; i < 5; i++) {
console.log(i);
}
Here, the for loop iterates the range of numbers from 0 to 4 and prints each number.
You use the while loop when the number of iterations isn't known or unpredictable. For example,
let number = Number(prompt("Enter a number: "));
while (number !== 0) {
console.log(`The number you entered is ${number}.`);
number = Number(prompt("Enter a number: "));
}
Here, we can't predict when the user will enter 0. Thus, the while loop is more suitable.
Sometimes, you don't want a loop to run until its natural end. In such cases, JavaScript provides the break and continue statements to control the flow of the loop.
These are especially useful when you need to exit early or skip certain iterations based on specific conditions.
You use break when you want to stop the loop early based on a specific condition. For example,
for (let number = 1; number <= 5; number++) {
// Stop the loop if the number is 3
if (number === 3) {
break;
}
console.log(number);
}
Output
1 2
Here, the loop starts from number = 1 to number <= 5, displaying each value of number. However, when number's value is 3, the loop terminates.
You use continue when you want to skip the current iteration based on a condition but keep the loop running for the remaining elements. For example,
for (let number = 1; number <= 5; number++) {
// Skip the loop if the number is 3
if (number === 3) {
continue;
}
console.log(number);
}
Output
1 2 4 5
In this case, when number's value is 3, the loop moves on to the next iteration. Thus, the value 3 isn't displayed on the console.
Efficient loop design can significantly improve the performance of your code.
Calculations or variables that don't change should be defined outside the loop to reduce redundant computations. For example,
Bad Practice
for (let i = 0; i < 5; i++) {
let result = Math.pow(2, 10); // Calculated in every iteration
console.log(result);
}
Here, the result variable is calculated inside the loop in every iteration, even though the calculation Math.pow(2, 10) always yields the same value (1024).
Good Practice
let result = Math.pow(2, 10); // Calculated once
for (let i = 0; i < 5; i++) {
console.log(result);
}
Here, the result variable is calculated outside the loop, avoiding unnecessary recalculations during each iteration.
For certain tasks like reversing sequences, looping in descending order can simplify logic and improve readability. For example,
for (let i = 5; i > 0; i--) {
console.log(i);
}
Output
5 4 3 2 1
Here, the loop iterates in reverse order, often useful for operations like countdowns or reverse processing.
When loops don't behave as expected, debugging becomes crucial. By tracking progress and identifying issues, you can pinpoint errors and fix them effectively.
Here are some techniques to debug your loops.
Use console.log() statements to monitor loop progress during debugging. For example,
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
console.log(`Iteration: ${i} ${j}`);
}
}
Output
Iteration: 0 0 Iteration: 0 1 Iteration: 0 2 Iteration: 0 3 Iteration: 0 4 Iteration: 1 0 Iteration: 1 1 ...
Here, the console.log() statement helps track the loop's current iteration, making debugging easier.
Ensure your loop has an achievable exit condition to avoid infinite loops.
let count = 0;
while (true) {
console.log("Running...");
count++;
if (count > 5) { // Exit after 5 iterations
break;
}
}
Output
Running... Running... Running... Running... Running... Running...
In this example, the count variable stops the loop after a fixed number of iterations, preventing an infinite loop.
for loop when the number of iterations is known, and the while loop when the number is unpredictable.break to stop a loop early and continue to skip iterations based on conditions.console.log() to track loop progress, ensuring efficient and error-free code.