Loops

Repeating an action multiple times without copy-pasting code.

What is it?

Often you need to do the same thing many times: print every item in a list, check every user, count from 1 to 100. Writing that out by hand is tedious and error-prone. A loop repeats a block of code for you, either a fixed number of times or until a condition is no longer true.

The two you'll use most:

  • for — when you know how many times to repeat (or you're going through a list)
  • while — when you want to repeat until some condition becomes false

Explain like I'm 10

A loop is like telling someone: 'Keep folding laundry until the basket is empty.' One instruction, repeated, instead of a new one for every item.

Examples

A basic for loop

for (let i = 1; i <= 5; i++) {
  console.log(i);
}
// logs 1, 2, 3, 4, 5

i = 1 sets the start, i <= 5 is the condition checked before each run, and i++ increases i after each run.

A while loop

let count = 3;
while (count > 0) {
  console.log(count);
  count = count - 1;
}
// logs 3, 2, 1

A for...of loop — looping over an array directly

const fruits = ["apple", "banana", "cherry"];

for (const fruit of fruits) {
  console.log(fruit);
}
// logs apple, banana, cherry

for...of loops over the values in an array (or any iterable), so there's no counter to manage and no off-by-one risk.

How it works

Before each pass, JavaScript checks the condition. If it's true, it runs the loop body and checks again. When the condition becomes false, the loop stops and the program continues after it.

Check condition
       ↓
  true? ──yes──▶ run loop body ──▶ back to check condition
    │
    no
    ↓
 exit loop

Why does it exist?

Loops let you write one block of logic and apply it to many items or repetitions, instead of duplicating code that's tedious to write and hard to change.

When to use it

Use a loop to repeat an action for every item in a collection, or to repeat something until a condition is met: processing a list, retrying a request, counting down a timer.

When not to use it

For a small, fixed number of repeats, a couple of plain statements can be clearer than a loop. And to transform or filter every item in an array, .map() and .filter() usually read better than a manual loop.

Common mistakes

  • Forgetting to update the loop variable, causing an infinite loop (e.g. forgetting i++).

  • Using <= vs < incorrectly and running one extra or one fewer time than intended (an 'off-by-one' error).

  • Modifying an array while looping over it, which can skip or repeat items.

Practice exercises

  1. Easy:

    Use a for loop to print the numbers 1 through 10.

  2. Medium:

    Use a while loop to add up all numbers from 1 to 100.

  3. Hard:

    Use a nested loop to print a 5x5 grid of * characters.

Interview questions

What's the difference between `for` and `while`?

A for loop puts the counter's setup, condition and update on one line, so it fits when you know how many times (or over what range) to repeat. A while loop has only a condition, checked before each pass, so it fits when repetition depends on something other than a simple counter.

What causes an infinite loop?

A condition that never becomes false. Usually the code that should change the tested value (like i++, or updating a flag in a while) is missing, runs on the wrong branch, or moves the value the wrong way.

What do `break` and `continue` do?

break exits the loop immediately; no more iterations run. continue skips the rest of the current iteration and jumps to the next condition check, without leaving the loop.

What is a `for...of` loop, and what does it iterate over?

A loop over the values of any iterable (arrays, strings, Maps, Sets) with no index variable, so there's no counter to manage and no off-by-one risk.

What's the difference between `for...of` and `for...in`?

for...of loops over an iterable's values (an array's elements, a string's characters). for...in loops over an object's enumerable property keys, as strings. On an array it gives indices as strings ("0", "1", ...), not values, so it's generally kept for plain objects.

What is a `do...while` loop, and how does it differ from a regular `while` loop?

It runs the body once before the first condition check, then checks before each later pass like a normal while. So the body always runs at least once, even if the condition is false from the start.

What is an 'off-by-one' error, and how does it typically happen in a loop?

Running a loop one time too many or too few, usually by using <= instead of < (or the reverse). For example, looping i <= array.length reads one index past the end of the array.

Why does modifying an array's length while looping over it with a classic indexed `for` loop cause bugs?

Adding or removing elements shifts the indexes of everything after them, while the loop index keeps advancing. So the loop can skip an element or process one twice, with no error to warn you.

Inside a nested loop, does a plain `break` exit both loops or just the inner one?

Just the inner one; a bare break exits only the nearest loop. To exit an outer loop from inside, use a label, like outer: for (...) { for (...) { break outer; } } .

Can you use `continue` inside a `for...of` loop?

Yes. It works as in any loop: it skips the rest of the current iteration and moves to the next value.

Why is `for...of` generally preferred over a classic indexed `for` loop when you just need each value?

It removes the bugs that come with managing an index by hand (off-by-one errors, wrong comparisons, forgetting to increment), and it reads directly as "for each value in this collection."

What's a key behavior difference between a classic `for` loop and `.forEach()`?

.forEach() calls a callback once per element, so each call has its own function scope, which works naturally with let/const closures. But break/continue/return can't control the iteration the way they do in a real loop: you can't stop a .forEach() early.

Can `break` be used inside `.forEach()`? Why or why not?

No. break only works inside real loops (for, while, do...while). .forEach() is a function called repeatedly, not loop syntax, so break in its callback is a SyntaxError. To stop early, use for...of with break, or a method like .some()/.find() that stops once satisfied.

Why does a `let` counter in a `for` loop create a new binding on every iteration, and why does that matter for closures?

The spec defines for (let i ...) to create a fresh i for each iteration (carrying over the previous value), instead of one shared binding. That lets a closure in the loop body, like a setTimeout callback, capture that iteration's own i, instead of all callbacks sharing one final value as with var.

Output-prediction: what does `for (let i = 0; i < 3; i++) { if (i === 1) continue; console.log(i); }` log?

It logs 0 then 2. When i is 1, continue skips the console.log and the loop moves on to i = 2.

Output-prediction: what does `outer: for (let i = 0; i < 2; i++) { for (let j = 0; j < 2; j++) { if (j === 1) continue outer; console.log(i, j); } } ` log?

It logs 0 0 then 1 0. When j is 1, continue outer jumps to the next outer iteration before the inner console.log runs, so each outer pass only logs j = 0.

Trap: what's wrong with `let i = 0; while (i < 5) { console.log(i); }`, and what actually happens when it runs?

It's an infinite loop that logs 0 forever. Nothing in the body changes i, so i < 5 stays true. It needs something like i++; inside the block.

Output-prediction: what does `const arr = ["a", "b", "c"]; for (const index in arr) { console.log(typeof index); }` log?

It logs "string" three times. for...in gives an array's property keys, and indices come as strings ("0", "1", "2"). That's one reason to prefer for...of or indexed access for arrays.