AlgoInsight

Free lesson · JavaScript Basic to Advance

Loops: for, while, do-while

Easy5 min read

Why Loops Exist

A loop is code that runs repeatedly until some condition tells it to stop. Loops are how you process collections of data, repeat actions, generate sequences, and build up results from smaller steps. Almost every non-trivial program uses loops.

JavaScript gives you several loop types, each suited to different situations:

This Topic covers the first three. The next Topic covers the array iteration patterns you'll use most often in modern JavaScript.

The Classic for Loop

The for loop is the workhorse of imperative programming. It has three parts inside the parentheses, separated by semicolons.

for (let i = 0; i < 5; i++) {
  console.log(`Iteration ${i}`);
}

Breaking down what's happening:

The order is: initialize, then check condition, then run body, then update, then check condition again, and so on. When the condition becomes false, the loop stops.

graph TD
    A[Start] --> B[Initialize: let i = 0]
    B --> C{Check condition:<br/>i < 5?}
    C -->|true| D[Run loop body]
    D --> E[Update: i++]
    E --> C
    C -->|false| F[End loop]

    style C fill:#7c3aed,color:#fff
    style D fill:#10b981,color:#fff
    style F fill:#dc2626,color:#fff
This diagram shows the execution flow of a for loop. The loop starts by running the initialization expression once. Then it checks the condition. If the condition is true, it runs the loop body, then runs the update expression, then checks the condition again. This cycle repeats until the condition becomes false, at which point the loop ends.

The for loop is well-suited to situations where you know in advance how many iterations you need, or where you need explicit access to the index.

Counting Down or by Different Amounts

The three parts of a for loop can be anything. You're not limited to counting up by one.

// Counting down
for (let i = 10; i > 0; i--) {
  console.log(i);
}
console.log("Liftoff!");

// Counting by twos
for (let i = 0; i <= 10; i += 2) {
  console.log(i);
}

// Iterating in reverse over an array
const names = ["Olena", "Nikhil", "Emeka"];
for (let i = names.length - 1; i >= 0; i--) {
  console.log(names[i]);
}

This flexibility is what makes for loops powerful. You can iterate in any direction, at any step size, with any starting and ending condition. The trade-off is that you have to write out all three parts, which makes simple iteration verbose.

For simple "do something to each element of an array" loops, modern JavaScript prefers forEach or for...of (next Topic). For complex iteration patterns, the classic for is still the right choice.

The while Loop

A while loop runs as long as its condition is true. It has no built-in initialization or update — you handle those yourself, before and inside the loop.

let count = 0;

while (count < 5) {
  console.log(`Count is ${count}`);
  count++;
}

This is equivalent to the basic for loop from earlier, just written differently. The variable count is initialized before the loop, the condition is checked at the top, and the update happens inside the body.

while is the right choice when you don't know how many iterations you'll need. The classic example is reading input until something specific happens:

function findFirstEven(numbers) {
  let i = 0;
  while (i < numbers.length && numbers[i] % 2 !== 0) {
    i++;
  }
  return i < numbers.length ? numbers[i] : null;
}

console.log(findFirstEven([1, 3, 5, 7, 4, 9]));   // 4
console.log(findFirstEven([1, 3, 5, 7]));         // null

The loop continues until it finds an even number or runs out of array. We don't know in advance how many iterations that will take — could be one, could be many. while is more natural here than for.

The Infinite Loop Trap

Because while doesn't force you to write an update expression, it's easy to write loops that never end. This is the classic beginner mistake:

// ⚠️ Don't run this — it loops forever
let n = 0;
while (n < 10) {
  console.log("Stuck");
  // forgot to increment n
}

The condition n < 10 is true. It will always be true, because nothing inside the loop changes n. Your browser tab will freeze. Your terminal will hang. You'll have to force-quit the process.

The fix is obvious once you see it — always make sure something inside the loop makes progress toward the exit condition. But every JavaScript developer has written this bug at least once. Don't feel bad when it happens. Just learn to spot it quickly.

Warning: If you suspect a loop might be infinite, save your work before testing. Browser dev tools have a "Stop" button, but it doesn't always work fast enough. A truly infinite loop will hang the tab. Be especially careful with while loops where the exit condition depends on complex logic.

The do...while Loop

do...while is identical to while, except it checks the condition after the body runs instead of before. This guarantees the body runs at least once, even if the condition is false from the start.

let count = 10;

do {
  console.log(`Count is ${count}`);
  count++;
} while (count < 5);

The condition count < 5 is false from the start (10 is not less than 5). But the body still runs once, because do...while doesn't check the condition until after.

This is useful when you need to do something at least once before deciding whether to repeat. The classic case is prompting a user for input — you have to ask once before you can decide whether to ask again.

let userInput;
do {
  userInput = prompt("Enter a positive number:");
} while (Number(userInput) <= 0);

You couldn't write this naturally with a while loop, because you wouldn't have a value to check on the first iteration. do...while solves that.

do...while is rare in real code — most situations are better served by while or for. But it exists for the cases where "run at least once" is exactly what you need.

Interactive animation: The same false condition under while and do-while - while runs zero times, do-while runs exactly once.

Choosing the Right Loop

Interactive animation: Choosing between for, while and do-while by asking what you know before the loop starts.

Some practical guidance:

Use for when you know how many iterations you need, or when you need explicit index control.

Use while when you're looping until a condition changes, and you don't know how many iterations that will take.

Use do...while when you need the body to run at least once regardless of the condition.

Use forEach or for...of (covered in the next Topic) when you're iterating over the elements of an array. These are the modern preferred styles for that common case.

Common Pitfalls

Interactive animation: One character too generous - a loop ending at i <= length runs one pass past the last element.

Warning: The classic loop mistakes.

Off-by-one errors. Should the loop end at i < length or i <= length? Should it start at i = 0 or i = 1? These mistakes are the most common bugs in real loop code. Trace through with small inputs (length 1, length 2, length 0) to catch them.

Modifying the array while iterating it. If you push or splice while looping, the indices shift and your loop gets confused. Either iterate over a copy or use the modern iteration methods that handle this more safely.

Forgetting the update in a while loop. Without an update inside the body, the condition never changes and the loop runs forever. Always verify before running: "what changes inside this loop that will eventually make the condition false?"

Why This Matters in Interviews

Interview: Loop construction is foundational for any coding interview. Interviewers expect you to write loops fluently without thinking about syntax. The signal they're looking for: do you reach for the right loop type for the situation? Using a classic for loop to iterate over an array suggests you haven't learned the modern array methods. Using a while for a fixed-count iteration suggests you don't know for exists.

Topic 4.6 — Interview Lens: Control Flow and Iteration Patterns — covers the deeper interview-prep treatment, including the iteration patterns that show up in DSA problems.

Try It

Exercise: Write three different loops that print the numbers 1 through 10. Use a for loop for the first, a while loop for the second, and a do...while loop for the third. They should all produce identical output.

Then, harder: write a loop that prints the numbers 1 through 100, but for multiples of 3 print "Fizz" instead, for multiples of 5 print "Buzz", and for multiples of both 3 and 5 print "FizzBuzz". This is the famous "FizzBuzz" problem — a common warm-up question in coding interviews. Get the logic right, then think about how you'd write it most cleanly.

Back to JavaScript Basic to Advance