JavaScript Loops Tutorial: For, While, and Do-While Explained
Learn JavaScript loops with clear examples: for, while, and do-while explained step by step for beginners.
Loops are one of the most essential concepts in JavaScript programming. They help you repeat tasks without writing the same code again and again. Whether you want to display numbers, process arrays, or wait for conditions to change, loops save time and make your code cleaner. In this tutorial, we’ll cover three fundamental loops in JavaScript: for, while, and do-while. Each has its own use cases, strengths, and syntax that every beginner must learn.
Table of Contents
- Getting Started with Loops
- The For Loop
- The While Loop
- The Do-While Loop
- Common Issues & Solutions
- Best Practices
Getting Started with Loops

illustrated diagram that visually compares how for, while, and do-while loops flow
A loop lets you execute a block of code multiple times. The repetition is controlled by a condition. If the condition is true, the loop runs; if it’s false, the loop stops. Without loops, you would need to copy-paste code many times, which is inefficient.
The For Loop
The for
loop is the most commonly used loop in JavaScript. It’s perfect when you know exactly how many times you want to repeat an action.
Syntax of a For Loop
for (initialization; condition; increment) {
// Code to run each time
}
- Initialization: Sets a starting point (e.g.,
let i = 0
). - Condition: The loop continues while this is
true
(e.g.,i < 5
). - Increment/Decrement: Updates the variable (e.g.,
i++
).
Example: Printing Numbers
for (let i = 1; i <= 5; i++) {
console.log("Number: " + i);
}
This will print numbers 1 to 5.
Example: Looping Through an Array
const fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
This prints each fruit name from the array.
The While Loop
The while
loop is useful when you don’t know how many times you’ll need to repeat something. It keeps running as long as the condition is true.
Syntax of a While Loop
while (condition) {
// Code to run
}
Example: Countdown
let count = 5;
while (count > 0) {
console.log("Countdown: " + count);
count--;
}
This will print a countdown from 5 to 1.
Example: Waiting for User Input Simulation
let password = "";
while (password !== "1234") {
// Imagine this is user input
password = "1234";
}
console.log("Access Granted!");
Here, the loop continues until the correct password is provided.
The Do-While Loop
The do-while
loop is similar to the while
loop, except it always runs at least once, even if the condition is false.
Syntax of a Do-While Loop
do {
// Code to run
} while (condition);
Example: Run Once Minimum
let number = 6;
do {
console.log("Number is: " + number);
number++;
} while (number < 5);
Even though number
starts at 6 (greater than 5), the loop still runs once.
Example: Menu Simulation
let option;
do {
option = "exit"; // simulate user choosing exit
console.log("Menu: Type 'exit' to quit");
} while (option !== "exit");
console.log("Program Ended");
This ensures the menu is displayed at least once.
Common Issues & Solutions
Infinite Loops
An infinite loop happens when the condition never becomes false.
while (true) {
// This will run forever unless you break manually
}
Fix: Ensure your loop variables update correctly.
Off-by-One Errors
Sometimes loops run one time too many or too few.
for (let i = 0; i <= 5; i++) { // Runs 6 times instead of 5
console.log(i);
}
Fix: Double-check loop conditions.
Best Practices
Use the Right Loop for the Job
- Use for loops when the number of iterations is known (like arrays).
- Use while loops when the end condition isn’t fixed.
- Use do-while when the loop must run at least once.
Avoid Infinite Loops
Always update variables inside loops, otherwise, they may never stop.
Keep Loops Simple
Don’t put too much logic inside a loop. Instead, call functions inside loops for clarity.
Use break
and continue
break
exits a loop immediately.continue
skips the current iteration and moves to the next.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue; // Skip number 3
if (i === 5) break; // Stop at 5
console.log(i);
}
This prints 1, 2, 4.
Frequently Asked Questions
Q: What is the difference between while and do-while loops in JavaScript?
A: A while loop checks the condition before running the code block, while a do-while loop runs the code block at least once before checking the condition.
Q: When should I use a for loop instead of a while loop?
A: Use a for loop when the number of iterations is known (like looping through an array), and a while loop when the number of iterations depends on a condition that may change dynamically.
Q: Can I break out of a loop in JavaScript?
A: Yes. You can use the break
statement to exit a loop immediately, or the continue
statement to skip the current iteration and move to the next one.
Q: Are infinite loops always bad in JavaScript?
A: Infinite loops are usually a mistake and can crash your program. However, they can be useful in cases like event loops, servers, or listeners when handled properly with conditions.
Conclusion
Key Takeaways
- Loops allow you to repeat tasks efficiently in JavaScript.
- Use
for
when you know the exact number of iterations. - Use
while
when the loop depends on a condition. - Use
do-while
when the loop must run at least once. - Always watch out for infinite loops.
Next Steps
- Practice writing small programs using all three loop types.
- Try looping through arrays and objects with
for
andwhile
. - Explore advanced loops like
for...in
andfor...of
. - Read the MDN JavaScript Loops Guide for deeper understanding.