for and while loops
The sum 1 + 2 + … + 100 can be written term by term, but that means typing a hundred numbers. Repeated actions are described by a loop, a construct that runs code again and again while a condition is true.
Picture a runner at a stadium. The coach says, "Keep running laps until you've done a hundred." Before each new lap, the runner passes a checkpoint arch that checks the count. Then comes the lap and a mark in a notebook.
A loop works the same way. The most common one is the for loop:
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log(sum); // 5050The three header parts
The parentheses after for hold three parts separated by semicolons:
let i = 1runs once, before the loop starts. The runner steps up to the start line.- The condition
i <= 100is checked before every pass. If it is true, the loop body in braces runs. This is the checkpoint arch before the lap. - The step
i++runs after the body. This is the mark in the notebook.
One pass through the body is called an iteration. Let's walk through the program line by line:
let sum = 0sets up the sum.for (let i = 1; i <= 100; i++)repeats the body untilibecomes101.sum += iadds the currentito the sum.console.log(sum)stands after the loop's closing brace. It runs once, when the loop has already finished, and prints the final sum5050.
The condition sets the number of iterations. With i < 3, the body runs for 1 and 2, and at 3 the condition is already false.
The order of the header parts is where beginners get confused most often. The widget runs the same loop with the condition i <= 3: press "Next step" and watch when each part of the header runs.
1let sum = 0;2 3for (let i = 1; i <= 3; i++) {4 sum += i;5}6 7console.log(sum);
let sum = 0 sets up the sum.
The step i++ runs after the body, and the condition runs before it. So the last check, 4 <= 3, is already false, and the body never runs with i equal to 4. The condition is also checked before the first pass: if it is false from the start, the body never runs.
Here the stadium picture is inexact. The runner keeps the notebook with its marks after the run, while the variable i disappears with the loop: at the widget's last step it is already gone.
The while loop
A while loop has only a condition in its parentheses. The variable is declared before the loop and changed in the body. This counts how many times 100 must be halved, rounding down, to leave 1:
let n = 100;
let steps = 0;
while (n > 1) {
n = Math.floor(n / 2);
steps++;
}
console.log(steps); // 6The values of n go 100, 50, 25, 12, 6, 3, 1. That is six divisions, and at 1 the condition n > 1 becomes false. You use while when the number of repetitions is not known in advance and depends on what happens in the body.
If the body never changes the variable in the condition, the condition stays true and the loop never ends. In the course exercises, such a program is stopped by the time limit. If you ran it yourself, stop it with Ctrl+C in the terminal.
There is also the form do { … } while (condition);. It checks the condition after the body, so the body runs at least once. For example, do { console.log("hi"); } while (false); prints hi once, although the condition is false from the start.
Interviewers sometimes ask how while differs from do…while. The difference is when the condition is checked: while checks it before the body, and do…while after it.
Common mistake
The loop variable is read after the loop:
for (let i = 0; i < 3; i++) {
console.log(i);
}
console.log(i); // ✗ReferenceError: i is not definedThe program prints 0, 1 and 2, then stops with this error, worded as Node and Chrome print it. A variable declared with let in the for header is visible only inside the loop, in the header and the body. If you need the value after the loop, declare the variable before it and change it inside, as in a while loop.
Key points
- A
forheader has three parts: the first runs once, the condition before every iteration, the step after the body. whilechecks only a condition, and the variable in it must change in the body, or the loop never ends.do…whilechecks the condition after the body, so the body runs at least once.- A variable declared with
letin theforheader is visible only inside the loop.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.