JavaScript: Loops

Repeat code efficiently with for loop, while loop, do while loop, for in loop, for of loop and plus break, continue, and loop safety.

for Loop

The for loop is the most common loop when the number of iterations is known in advance. Its header has three parts: initialiser, condition, and increment: all in one line.

for Loop

Best when you know the exact iteration count: counter is declared and managed in the header.

  • Syntax: for (init; condition; increment) { }
  • Initialiser runs once before the loop starts
  • Condition is checked before each iteration: loop stops when false
  • Increment runs after each iteration
  • Use let for the counter: block-scoped to the loop

for Loop

The counter i is scoped to the loop: it does not exist outside the for block.

while Loop

The while loop repeats as long as its condition is truthy. It is the right choice when the number of iterations is not known in advance: such as reading input until a sentinel value is received.

while Loop

Condition-first loop: best when iteration count is unknown.

  • Condition is evaluated before each iteration
  • If the condition is false on entry the body never runs
  • You must update the condition variable inside the loop or it runs forever
  • Common use: processing data until a specific value is encountered

while Loop

Always ensure the condition eventually becomes false: a missing update is the most common bug.

do while Loop

do while loop is like while but checks the condition after the body executes. This guarantees the body runs at least once regardless of the condition.

do while Loop

Condition-last loop: body always runs at least once.

  • Body executes first, then condition is checked
  • Use when the action must happen before the first check
  • Classic use case: prompt the user until they give valid input
  • Less common than while, but the right tool when "run at least once" is required

do while Loop

The body executes before the condition is ever checked: guaranteed first run.

for in Loop (Objects)

for in loop iterates over the enumerable keys of an object. It is designed for plain objects: avoid using it on arrays, where index order is not guaranteed and inherited properties can appear.

for in Loop

Iterates object keys: avoid on arrays, use for plain objects only.

  • Gives the key (property name) on each iteration
  • Access the value with obj[key]
  • Also iterates inherited enumerable properties: use hasOwnProperty to filter
  • Do not use on arrays: use for of loop or forEach instead

for in Loop: Object Keys

for in loop gives keys as strings: use obj[key] to get the value.

for of Loop (Iterables)

for of loop iterates over the values of any iterable: arrays, strings, Maps, Sets, and more. It is the modern, preferred loop for arrays.

for of Loop

Iterates values of any iterable: the preferred loop for arrays and strings.

  • Works on: arrays, strings, Maps, Sets, NodeLists, generators
  • Gives values directly: no index management needed
  • Use entries() to get both index and value: for (const [i, v] of arr.entries())
  • Does NOT work on plain objects: use for in loop or Object.entries()

for of Loop: Iterable Values

for of loop is cleaner than a for loop for arrays: use entries() when you also need the index.

break Statement

break immediately exits the nearest enclosing loop or switch statement. It is used to stop looping early once a desired condition is met.

break

Exits the loop immediately: execution resumes after the loop body.

  • Exits only the innermost loop: use labels for nested loops
  • Common use: search loops: stop once the target is found
  • Also required in switch cases to prevent fall-through
  • Overusing break is a code smell: consider restructuring the condition

break Statement

break is ideal for search loops: stop as soon as the answer is found.

continue Statement

continue skips the rest of the current iteration and jumps to the next one. It does not exit the loop: the loop carries on from the next cycle.

continue

Skips one iteration: the loop continues with the next value.

  • Only skips the current iteration: the loop still runs
  • Common use: filter out unwanted values without nesting
  • Makes code flatter: avoids wrapping the body in an if block
  • In a for loop, the increment still runs after continue

continue Statement

continue flattens the loop body: instead of if (condition) { ... } wrap, just skip early.

Nested Loops

A loop inside another loop is called a nested loop. The inner loop runs its full cycle for every single iteration of the outer loop. This is commonly used to process 2D data like grids and matrices.

Nested Loops

Inner loop completes fully on every outer iteration: total iterations multiply.

  • With outer n and inner m iterations: total = n × m
  • Use different variable names: i for outer, j for inner
  • break inside the inner loop only exits the inner loop
  • Keep nesting to two levels max: deeper nesting signals a refactor is needed

Nested Loops

3 outer × 3 inner = 9 total iterations: total cost multiplies, not adds.

Infinite Loops and Prevention

An infinite loop runs forever because its condition never becomes false. It will freeze the browser tab or crash a Node.js process. Knowing the patterns that cause them is the first step to prevention.

Infinite Loop Causes

Three patterns that produce infinite loops: avoid all three.

  • Missing increment: for (let i = 0; i < 10;), i never changes
  • Condition always true: while (true) without a break
  • Wrong update direction: for (let i = 0; i > -1; i++), grows forever
  • Prevention: always ensure the loop variable moves toward making the condition false

Safe Infinite Loop Pattern

while(true) is only safe with a guaranteed break: add a max-iteration guard for extra safety.

Loop Performance Considerations

For most applications loops are fast enough that micro-optimisation is unnecessary. However a few habits prevent accidental slowdowns, especially in loops over large datasets.

Loop Performance Tips

Cache expensive values outside the loop: avoid DOM access or heavy computation per iteration.

  • Cache array.length before the loop: const len = arr.length;: avoids re-reading on every iteration
  • Avoid DOM reads/writes inside loops: batch them outside
  • Prefer built-in methods (map, filter, reduce) over manual loops: engines optimise them heavily
  • Break early when the result is found: no need to process remaining items
  • Avoid creating objects or closures inside a hot loop: GC pressure adds up

Loop Performance

Run this to compare: the difference grows significantly on large arrays.

Loop typeBest forAvoid when
forKnown count, index neededSimple array iteration
whileUnknown count, condition-drivenYou know the exact count
do while loopMust run at least onceCondition may be false initially
for in loopPlain object keysArrays (use for of loop)
for of loopArrays, strings, iterablesPlain objects
forEach / mapFunctional array transformsNeed to break early

Knowledge Check

1. What are the three parts of a for loop header?

2. What is the key difference between while and do while loop?

3. What does for loop in iterate over?

4. What does for loop of iterate over?

5. What does the break statement do inside a loop?

6. What does the continue statement do?

7. What is the most common cause of an infinite loop?

8. Which loop type is best when you do not know how many iterations are needed in advance?