Mastering JavaScript Loops: A Comprehensive Guide
Unlocking the Power of while Loops
The while loop is a fundamental concept in JavaScript that allows you to execute a block of code repeatedly as long as a specified condition is true. The syntax is simple: while (condition) { code to be executed }
. But what makes it tick?
How while Loops Work
Here’s a step-by-step breakdown:
- The condition is evaluated. If it’s true, the code inside the loop is executed.
- The condition is re-evaluated. If it’s still true, the code runs again.
- This process continues until the condition becomes false, at which point the loop stops.
Example 1: Counting from 1 to 3
Let’s put this into practice with a simple example. We’ll display numbers from 1 to 3 using a while loop.
var i = 1;
while (i <= 3) {
console.log(i);
i++;
}
Understanding Loop Conditions
To master while loops, you need to grasp loop conditions. Visit our article on JavaScript Comparison and Logical Operators to learn more.
Example 2: Summing Positive Numbers
In this example, we’ll use a while loop to sum only positive numbers entered by the user.
var sum = 0;
var num = parseInt(prompt("Enter a number"));
while (num > 0) {
sum += num;
num = parseInt(prompt("Enter a number"));
}
console.log("Sum of positive numbers: " + sum);
Introducing do…while Loops
The do…while loop is similar to the while loop, but with a twist. It executes the code block once before evaluating the condition.
How do…while Loops Work
Here’s how it works:
- The code inside the loop is executed once.
- The condition is evaluated. If it’s true, the code runs again.
- This process continues until the condition becomes false, at which point the loop stops.
Example 3: Counting Down from 3
Let’s demonstrate the do…while loop with an example that displays numbers from 3 to 1.
var i = 3;
do {
console.log(i);
i--;
} while (i > 0);
Key Differences between while and do…while Loops
The main difference between the two loops is that the do…while loop executes its body at least once, even if the condition is false.
Example 4: Summing Positive Numbers (Again!)
In this example, we’ll use a do…while loop to sum positive numbers entered by the user.
var sum = 0;
var num;
do {
num = parseInt(prompt("Enter a number"));
if (num > 0) {
sum += num;
}
} while (num > 0);
console.log("Sum of positive numbers: " + sum);
Avoiding Infinite Loops
Be careful not to create infinite loops, which can cause your program to hang. Make sure to set a condition that will eventually become false.
Choosing the Right Loop
When to use a while loop? When the termination condition varies. When to use a for loop? When you need to perform a fixed number of iterations.
More on JavaScript Loops
Want to learn more about JavaScript loops? Check out our articles on the break and continue statements.