JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
A loop is a way to repeat a block of code without writing it over and over. Instead of copying the same five lines ten times, you write the code once and tell JavaScript to run it ten times.
JavaScript loops all share the same basic idea: keep running a block of code while a condition is true. The moment the condition becomes false, the loop stops. What changes between loop types is where you define the condition and when the code runs.
The diagram above shows a simple way to decide which loop to use. If you know the exact number of iterations ahead of time, a for loop is the cleanest choice.
If a condition needs to be true before the first run, use while. If the code inside the loop must execute at least once regardless of the condition, reach for do while.
The Three Core Loop Types
| Loop | When to Use | Checks Condition |
|---|---|---|
| for | You know the exact count | Before every iteration |
| while | You do not know the count | Before every iteration |
| do while | Body must run at least once | After every iteration |
All three loops can solve most repetition problems. The difference is about readability and intent. Choosing the right one makes your code easier to understand at a glance.
The for Loop
A for loop bundles the setup, condition, and update into one line. This is the loop you will write most often.
for (let i = 0; i < 3; i++) {
console.log("Iteration:", i);
}Each pass checks the condition before running the body, so the loop executes while i is 0, 1, and 2, then stops once i reaches 3. Running this prints:
Iteration: 0
Iteration: 1
Iteration: 2The for loop header has three parts, separated by semicolons:
-
Initialization (
let i = 0) -- runs once before the loop starts. -
Condition (
i < 3) -- checked before every iteration. If false, the loop exits. -
Update (
i++) -- runs after every iteration, before the next condition check.
Think of i as a counter. It starts at 0, goes up by 1 each time, and the loop stops when it reaches 3. This pattern -- start at 0, run while less than a number, increment by 1 -- is the most common loop pattern in JavaScript.
The while Loop
A while loop only has a condition. As long as the condition is true, the body runs.
let count = 0;
while (count < 3) {
console.log("Count is:", count);
count++;
}The condition is checked before each pass, so the body runs while count is 0, 1, and 2, then stops on the fourth check. Output:
Count is: 0
Count is: 1
Count is: 2Unlike a for loop, the while loop keeps the counter variable and the update step separate from the condition. This is useful when you do not know how many iterations you need ahead of time.
A common real-world example is reading data until you hit the end:
let hasMoreData = true;
let page = 1;
while (hasMoreData) {
console.log("Fetching page", page);
page++;
if (page > 3) hasMoreData = false;
}The loop keeps fetching pages until some external condition tells it to stop. You could not write this with a for loop because you do not know the page count in advance.
The do while Loop
A do while loop guarantees the body runs at least once, because the condition is checked after the body.
let num = 5;
do {
console.log("Number is:", num);
num++;
} while (num < 3);The condition is false from the very start, but a do while loop always runs the body one time before it checks anything. Output:
Number is: 5Even though num starts at 5 and 5 < 3 is false, the body still runs once. After that first run, JavaScript checks the condition, finds it false, and exits.
This loop is rarer than for and while, but it is the correct choice when you always need one execution before checking anything. A common use case is prompting a user for input and validating it after they respond:
let userInput;
do {
userInput = prompt("Enter a number greater than 10:");
} while (userInput !== null && Number(userInput) <= 10);
console.log("Accepted:", userInput);The prompt appears at least once. If the user enters an invalid number, it appears again. The condition is only meaningful after the first response exists.
Choosing the Right Loop
| Situation | Best Loop | Reason |
|---|---|---|
| Iterating over a known range | for | Clean, all controls in one line |
| Waiting for an external change | while | No counter needed |
| Validating user input | do while | Must prompt at least once |
| Counting through an array | for | Array length gives exact count |
| Retrying a failed operation | while | Unknown retry count |
| Menu that must display once | do while | Show menu before checking exit |
The for loop covers most everyday iteration. When you need to loop through every item in an array, learn how to loop through arrays using for loops. The while loop is your tool for situations where the number of iterations depends on something outside your control.
Avoiding Infinite Loops
An infinite loop happens when the condition never becomes false. The browser tab freezes, and the only way out is to close it.
The most common cause is forgetting to update the counter inside the loop body:
// DANGEROUS: infinite loop, count never changes
let count = 0;
while (count < 10) {
console.log(count);
// Missing: count++
}Always check that your loop body moves the condition toward false. For a for loop, check that the update step actually progresses.
For a while loop, make sure something inside the body changes the variable in the condition. For more detail, see how to avoid infinite loops in JavaScript.
Loop Control: break and continue
Two keywords give you extra control inside any loop type.
break exits the loop immediately, no matter the condition:
for (let i = 0; i < 10; i++) {
if (i === 4) {
break;
}
console.log(i);
}
// Prints: 0, 1, 2, 3continue skips the rest of the current iteration and jumps straight to the next one, without exiting the whole loop the way break does:
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue;
}
console.log(i);
}
// Prints: 0, 1, 3, 4The number 2 is skipped because continue tells the loop to stop that iteration early and move to i = 3. For a deeper look at these, read about the JavaScript break statement and the JavaScript continue statement.
Recap
Loops are the core mechanism for repeating code in JavaScript. The for loop gives you the most structure and is the right default choice.
The while loop handles unknown iteration counts, and the do while loop guarantees at least one run. Once you understand all three, you can express any repetition pattern clearly and safely.
Rune AI
Key Insights
- Loops repeat a block of code until a condition is met.
- Use a for loop when you know how many times to iterate.
- Use a while loop when you are waiting for an external condition.
- Use a do while loop when the body must run at least once.
- Always ensure the loop condition eventually becomes false to avoid infinite loops.
Frequently Asked Questions
Which loop should I use as a beginner?
Can I put a loop inside another loop?
What happens if a loop never stops?
Conclusion
JavaScript gives you three loop types: for loops when you know the count, while loops when you are waiting for a condition, and do while loops when the code must run at least once. Understanding all three lets you pick the right tool for any repetition task.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.
JS for Loop Syntax: A Complete Guide for Beginners
The for loop is the most common way to repeat code in JavaScript. Learn the three-part syntax, how each part works, and how to write clean, readable for loops.