Control flow: decisions and loops · Part 5 of 36

Loops: repeating work

Basic 14 min

while and for loops, ranges, iterating over collections, break/continue and how to avoid endless loops.

What you will learn

  • You can write while and for loops in both languages.
  • You can loop over a range of numbers and over the items of a list.
  • You can stop a loop early and recognise an infinite loop.

Before this: Decisions with if, else and booleans

Why loops?

If you want to water 30 pots, you don't write "water pot" 30 times. You write it once and tell the computer to repeat it. Repetition is what makes computers useful: they do the same thing a billion times without getting bored.

A toy car going round a circular track, lap after lap

The while loop

A while loop repeats as long as a condition is true:

let litres = 0;
while (litres < 10) {
  litres = litres + 3;
}
console.log(litres); // 12
litres = 0
while litres < 10:
    litres += 3
print(litres)  # 12

The condition is checked before each round. After four rounds litres is 12, the condition is false, and the loop ends.

The for loop over a range

When you know how many rounds you need, use for:

for (let i = 0; i < 5; i++) {
  console.log(i);   // 0, 1, 2, 3, 4
}
for i in range(5):
    print(i)        # 0, 1, 2, 3, 4

JavaScript's classic for has three parts: start (let i = 0), condition (i < 5) and step (i++, short for i = i + 1). Python's range(5) produces 0 to 4; range(2, 10, 2) gives 2, 4, 6, 8. Notice the pattern: start included, end excluded — the same rule as string slices.

Looping over a collection

Most of the time you want each item of a list:

const plants = ["basil", "mint", "thyme"];
for (const plant of plants) {
  console.log(plant);
}
plants = ["basil", "mint", "thyme"]
for plant in plants:
    print(plant)

Careful in JavaScript: for…of gives the values; for…in gives the keys (indexes as strings) and is meant for objects. If you need index and value, use plants.entries() in JavaScript or enumerate(plants) in Python.

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of the current round and starts the next one.
for n in range(1, 100):
    if n % 7 != 0:
        continue      # skip numbers not divisible by 7
    print("first multiple of 7:", n)
    break

Infinite loops

If the condition never becomes false, the loop never ends and the program "hangs". Typical causes: forgetting to change the variable (while (i < 10) without i++), or changing it in the wrong direction. That is why the sandbox in this lesson stops any program after a short time limit. In real programs, check that every loop makes progress towards its end.

Counting and summing

The most common loop pattern is the accumulator: start with a neutral value and update it each round.

total = 0
for price in [2.5, 4.0, 1.2]:
    total += price

Both languages have shortcuts for common cases (sum(prices) in Python, prices.reduce((a, b) => a + b, 0) in JavaScript) — you will meet them in the functions module.

Try it: JavaScript sandbox

Write and run small JavaScript programs; the checker tells you when an exercise is solved.

Turn on JavaScript to use this lab. Worked example:

Exercise 5: print the sum of all numbers from 1 to 100 using a loop. The expected output is 5050 — the sum young Gauss is said to have found by pairing 1 + 100, 2 + 99 and so on.

A loop drawn as a flow chart: check the condition, run the body, update, back to the check
Every loop: check, run, update, check again

Key points

  • while repeats while a condition is true; the condition is checked before each round.
  • for (let i = 0; i < n; i++) and for i in range(n) count from 0 to n − 1.
  • for…of (JavaScript) and for … in (Python) loop over the items of a collection.
  • break exits a loop, continue jumps to the next round.
  • Every loop must make progress, or it runs forever.

Flashcards

Question: What does range(5) produce in Python?
Answer: 0, 1, 2, 3, 4.
Question: Which JavaScript loop gives the values of an array?
Answer: for…of (for…in gives the keys).
Question: What does continue do?
Answer: Skips the rest of the current round and starts the next.
Question: What is the accumulator pattern?
Answer: Start with a neutral value (0, "", []) and update it in each round of the loop.

Check yourself

Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.

  1. How many times does the body of `for i in range(2, 10, 2)` run?

    Show the answer

    4

    range(2, 10, 2) yields 2, 4, 6, 8 — four values.

    Source: The Python Tutorial, 4.3 range()

  2. Which JavaScript loop is the right one to visit every value of an array?

    • for…of
    • for…in
    • do…until
    • foreach…as
    Show the answer

    for…of

    for…of iterates over values of iterables such as arrays; for…in iterates over property keys.

    Source: MDN, Loops and iteration

  3. Put the steps of one round of a classic JavaScript for loop in order (after the start).

    Show the answer

    Check the condition → Run the body → Run the step (i++)

    The condition is checked first; if true, the body runs; then the step expression runs before the next check.

    Source: MDN, for statement

  4. A while loop never ends. What is the most likely cause?

    • The loop variable is never changed
    • The loop has a break
    • The body prints something
    • The condition uses <
    Show the answer

    The loop variable is never changed

    If nothing in the body moves the condition towards false, the loop repeats forever.

    Source: MIT OCW 6.100L

Sources

Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.