Mastering JavaScript Loops
Learn how to use JavaScript loops like for, while, and do…while to handle repetitive tasks efficiently.
In programming, there are often situations where you need to repeat an action multiple times. For example, imagine you want to display the message “Hello, world!” ten times in the console. While you could write console.log("Hello, world!");
ten times, that would be very inefficient. Fortunately, JavaScript provides a better solution: loops.
Loops allow you to execute a block of code repeatedly, making your code more concise and saving you time.
The for
Loop
The most common type of loop in JavaScript is the for
loop. Here’s how it’s structured:
for (initialization; condition; final-expression) {
// Code to be executed repeatedly
}
Let’s break this down:
Initialization: You declare a loop counter variable and set its initial value (e.g.,
let i = 0
). This runs once at the start of the loop.Condition: This boolean expression is checked before each iteration. If it’s
true
, the loop continues; if it'sfalse
, the loop stops.Final expression: This expression is executed after each iteration, typically to update the loop counter (e.g.,
i++
).
Here’s an example to print “Hello, world!” ten times:
for (let i = 0; i < 10; i++) {
console.log("Hello, world!");
}
In this code:
The loop starts with
i
set to 0.The condition
i < 10
ensures that the loop runs as long asi
is less than 10.At the end of each iteration,
i
is incremented by 1 (i++
), and the message is logged to the console.
The while
Loop: Repeating Until a Condition is False
Another type of loop is the while
loop, which keeps executing a block of code as long as a specified condition is true.
while (condition) {
// Code to be executed repeatedly
}
Here’s an example where we count down from 10 to 1:
let count = 10;
while (count > 0) {
console.log(count);
count--; // Decrease the count by 1 in each iteration
}
The do...while
Loop: Guaranteed at Least One Execution
The do...while
loop is similar to the while
loop, but it guarantees that the code block runs at least once, even if the condition is initially false.
do {
// Code to be executed repeatedly
} while (condition);
This loop is useful in situations where you need to perform an action once before checking a condition.
Avoid Infinite Loops
An infinite loop occurs when the loop’s condition never becomes false, causing the code to run endlessly, which can crash your browser. Always ensure your loops have a way to stop.
// This loop runs forever since the condition is always true
for (let i = 0; i >= 0; i++) {
console.log("This will print forever!");
}
for...in
and for...of
Loops: Working with Objects and Arrays
JavaScript also provides specialized loops for working with objects and arrays:
for...in
: Iterates over the enumerable properties of an object.for...of
: Iterates over the iterable values of an array or other iterable objects (e.g., strings, sets, maps).
Controlling Loops with break
and continue
Sometimes, you need to control the flow of a loop. JavaScript provides the break
and continue
statements for this:
break
: Immediately exits the loop.continue
: Skips the current iteration and moves to the next one.
Here’s an example of both:
// Using break to stop the loop early
for (let i = 0; i < 10; i++) {
console.log(i);
if (i === 5) {
console.log("Stopping the loop at 5");
break; // Exits the loop when i reaches 5
}
}
// Using continue to skip odd numbers
for (let i = 0; i < 10; i++) {
if (i % 2 !== 0) { // Check if i is odd
continue; // Skip this iteration if i is odd
}
console.log(i); // Print even numbers only
}
Exercises: Practice with Loops
Here are some exercises that you can solve to practice all three types of loops that we discussed here:
Print Even Numbers: Write a
for
loop to print all even numbers from 2 to 20.Calculate Factorial: Use a
while
loop to calculate the factorial of a given number (e.g., 5! = 5 * 4 * 3 * 2 * 1 = 120).Guess the Number Game: Create a simple game where the user guesses a randomly generated number. Use a
do...while
loop to keep asking for guesses until they guess correctly.
Conclusion
Loops are an essential part of programming, and mastering them will help you write more efficient and powerful code. From for
loops to while
loops and beyond, each type of loop serves a specific purpose, allowing you to handle repetitive tasks easily.
If you’d like to learn more concepts and best practices of JavaScript, then feel free to check out my Free JavaScript Course.