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.

6 min read

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.

JavaScript loop decision flow

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

LoopWhen to UseChecks Condition
forYou know the exact countBefore every iteration
whileYou do not know the countBefore every iteration
do whileBody must run at least onceAfter 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.

javascriptjavascript
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:

texttext
Iteration: 0
Iteration: 1
Iteration: 2

The for loop header has three parts, separated by semicolons:

  1. Initialization (let i = 0) -- runs once before the loop starts.

  2. Condition (i < 3) -- checked before every iteration. If false, the loop exits.

  3. 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.

javascriptjavascript
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:

texttext
Count is: 0
Count is: 1
Count is: 2

Unlike 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:

javascriptjavascript
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.

javascriptjavascript
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:

texttext
Number is: 5

Even 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:

javascriptjavascript
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

SituationBest LoopReason
Iterating over a known rangeforClean, all controls in one line
Waiting for an external changewhileNo counter needed
Validating user inputdo whileMust prompt at least once
Counting through an arrayforArray length gives exact count
Retrying a failed operationwhileUnknown retry count
Menu that must display oncedo whileShow 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:

javascriptjavascript
// 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:

javascriptjavascript
for (let i = 0; i < 10; i++) {
  if (i === 4) {
    break;
  }
  console.log(i);
}
// Prints: 0, 1, 2, 3

continue skips the rest of the current iteration and jumps straight to the next one, without exiting the whole loop the way break does:

javascriptjavascript
for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue;
  }
  console.log(i);
}
// Prints: 0, 1, 3, 4

The 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

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.
RunePowered by Rune AI

Frequently Asked Questions

Which loop should I use as a beginner?

Start with the for loop. It keeps the start condition, stop condition, and step all in one line, which makes it the easiest to read and debug. Use while when you do not know how many times you need to loop in advance.

Can I put a loop inside another loop?

Yes. This is called a nested loop. The inner loop runs completely for every single iteration of the outer loop. It is common when working with grids, tables, or multi-dimensional arrays.

What happens if a loop never stops?

You get an infinite loop. The browser tab will freeze or crash. Always make sure your loop condition eventually becomes false, or use a break statement to exit early.

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.