Understanding Loops in JavaScript
Loops allow us to execute a block of code repeatedly. This is useful when you want to run the same code multiple times with different values or conditions.
JavaScript provides several types of loops. In this lesson, we will cover the most common ones:
- for loop
- while loop
- do-while loop
The for
Loop
The for
loop is best when you know beforehand how many times you want to run the loop.
for (let i = 1; i <= 5; i++) {
console.log("Iteration:", i);
}
Output:
Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4 Iteration: 5
Explanation:
let i = 1
→ loop starts at 1i <= 5
→ runs while condition is truei++
→ increasesi
by 1 on each loop
Q: What happens if we change i <= 5
to i < 5
?
A: The loop will run from 1 to 4, not 1 to 5. Because i = 5
is not less than 5.
The while
Loop
The while
loop is useful when you don’t know in advance how many times you need to loop.
let count = 1;
while (count <= 3) {
console.log("Count is", count);
count++;
}
Output:
Count is 1 Count is 2 Count is 3
Explanation: The while
loop checks the condition before each run. If count <= 3
is true, it enters the loop.
Q: What happens if we forget count++
?
A: The loop becomes infinite because the condition count <= 3
will always be true. This is a common beginner mistake.
The do-while
Loop
The do-while
loop is similar to while
, but it runs at least once before checking the condition.
let x = 6;
do {
console.log("x is", x);
x++;
} while (x <= 5);
Output:
x is 6
Explanation: Even though x <= 5
is false from the start, the loop body executes once before the condition is checked.
Q: When should you use do-while
instead of while
?
A: Use do-while
when you need the code to run at least once regardless of the condition.
Loop Comparison Table
Loop Type | Condition Checked | Runs at least once? | Best Use Case |
---|---|---|---|
for |
Before loop body | No | Known number of iterations |
while |
Before loop body | No | Unknown number of iterations |
do-while |
After loop body | Yes | Need to run at least once |
Conclusion
JavaScript loops are essential for automating repetitive tasks. Start with for
loops, move to while
for more dynamic conditions, and use do-while
when an action must be guaranteed at least once.
In the next lesson, we’ll explore functions in JavaScript and how they help structure your code efficiently.