⬅ Previous Topic
JavaScript Control Flow: if, else, switchNext Topic ⮕
JavaScript For Loop Examples⬅ Previous Topic
JavaScript Control Flow: if, else, switchNext Topic ⮕
JavaScript For Loop ExamplesLoops 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
LoopThe 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++
→ increases i
by 1 on each loopi <= 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.
while
LoopThe 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.
count++
?A: The loop becomes infinite because the condition count <= 3
will always be true. This is a common beginner mistake.
do-while
LoopThe 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.
do-while
instead of while
?A: Use do-while
when you need the code to run at least once regardless of the condition.
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 |
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.
⬅ Previous Topic
JavaScript Control Flow: if, else, switchNext Topic ⮕
JavaScript For Loop ExamplesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.