edubun 한국어

Loops: for and while

Adding up the whole numbers from 1 to 100 by hand takes a while. A three-line for loop does it at once and prints 5050.

Doing the same thing many times

Printing the numbers 1 to 5 with five console.log lines is fine. Printing 1 to 1,000 that way is not. A loop runs the same block of code again and again, changing a little each time, until a condition says stop. Loops are where computers earn their keep: they never get bored and never lose count.

The for loop

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

The parentheses after for hold three parts separated by semicolons. The first, let i = 1, runs once before the loop starts and creates a counter variable. The second, i <= 5, is the condition, checked before every round; when it becomes false, the loop ends. The third, i++, runs after every round and moves the counter on. One pass through the block is called an iteration. Trace it: i is 1, the condition is true, 1 is printed, i becomes 2, and so on until i becomes 6, the condition is false, and the program carries on after the closing brace.

The counter is usually called i, a tradition from mathematics, but any name works. You can count in other steps too: for (let i = 10; i >= 0; i -= 2) counts down 10, 8, 6, 4, 2, 0.

Building up a total

The most common loop pattern is the accumulator. Make a variable before the loop, update it inside, and use it after. Here is the sum from the lead:

let sum = 0;
for (let i = 1; i <= 100; i++) {
  sum += i;
}
console.log(sum);   // 5050

Notice where each line sits. If let sum = 0 were inside the loop, sum would be reset on every iteration. If console.log were inside, it would print 100 running totals instead of one answer. Before and after the loop are as important as the loop itself.

The while loop

A while loop has only a condition. It keeps running its block as long as the condition is true. Use it when you do not know in advance how many rounds you need, such as doubling a number until it passes 1,000.

let n = 1;
let steps = 0;
while (n <= 1000) {
  n *= 2;
  steps++;
}
console.log(n, steps);   // 1024 10

Something inside a while loop must eventually make the condition false. If you forget the line that changes n, the condition stays true forever. This is an infinite loop, and the page freezes. If that happens in a practice box, reload the page and fix the code. With a for loop the update step is written in the header, which makes this mistake rarer.

break and continue

Two keywords change the flow inside a loop. break leaves the loop at once. continue skips the rest of the current iteration and jumps to the next one. For example, a loop over 1 to 10 with if (i % 3 === 0) continue; at the top prints every number except 3, 6 and 9.

Worked example. How many numbers from 1 to 50 are multiples of 7? Start let count = 0, loop i from 1 to 50, and inside write if (i % 7 === 0) count++;. After the loop count is 7: they are 7, 14, 21, 28, 35, 42 and 49.

for (start; condition; update) { body } for (let i = 1; i <= 5; i++)

loopCode that runs a block again and again
iterationOne pass through the loop body
counterThe variable that counts rounds, often i
accumulatorA variable built up inside a loop, like sum
whileRepeats while a condition is true
infinite loopA loop whose condition never becomes false
breakLeave the loop now
continueSkip to the next iteration
  1. How many lines does this print?
    for (let i = 0; i < 4; i++) {
      console.log(i);
    }
  2. What is the last number printed?
    for (let i = 0; i < 4; i++) {
      console.log(i);
    }
  3. What does this print?
    let total = 0;
    for (let i = 1; i <= 4; i++) {
      total += i;
    }
    console.log(total);
  4. What does this print?
    let p = 1;
    for (let i = 1; i <= 5; i++) {
      p *= 2;
    }
    console.log(p);
  5. What does this print?
    let n = 10;
    while (n > 3) {
      n -= 3;
    }
    console.log(n);
  6. How many lines does this print?
    for (let i = 10; i >= 0; i -= 2) {
      console.log(i);
    }
  7. What does this print?
    for (let i = 1; i <= 10; i++) {
      if (i === 4) break;
      console.log(i);
    }
    • 1 2 3 on separate lines
    • 1 to 10 except 4
    • 1 2 3 4 on separate lines
  8. How many lines does this print?
    for (let i = 1; i <= 10; i++) {
      if (i % 2 === 0) continue;
      console.log(i);
    }
  9. What is wrong with this loop?
    let i = 0;
    while (i < 5) {
      console.log(i);
    }
    • Nothing
    • i never changes, so it never stops
    • It prints nothing
  10. What does this print?
    let count = 0;
    for (let i = 1; i <= 50; i++) {
      if (i % 7 === 0) count++;
    }
    console.log(count);
Key points
  • for (start; condition; update) { ... } repeats while the condition is true.
  • Make accumulators before the loop, update them inside, use them after.
  • while (condition) { ... } suits loops with an unknown number of rounds.
  • Something must make the condition false, or the loop never ends.
  • break leaves the loop; continue skips to the next round.