Introduction
Computers are valuable because they repeat work without getting tired or careless. Without loops, printing a times table would need a separate line for each row, and handling a list you have not seen yet would be impossible. A loop runs the same code again and again, with a value that changes each time.
How it works
for: counting.
for (let i = 1; i <= 5; i++) {
// runs with i = 1, 2, 3, 4, 5
}
The three parts are the start (runs once), the condition (checked before each pass; the loop ends when it is false) and the update (after each pass). i++ adds 1 to i.
while: until something happens. while (condition) { ... } repeats as long as the condition is true, so it fits loops where the number of passes is not known in advance. do { ... } while (condition) is the same but always runs at least once.
// Add up the digits of a number with a while loop.
let number = 4821;
let sum = 0;
while (number > 0) {
const digit = number % 10; // the last digit
sum += digit;
number = Math.floor(number / 10); // drop the last digit
}
console.log("The digits add up to", sum);Each pass here removes one digit, which is what guarantees that the loop will finish.
for...of: every item. for (const item of list) gives each item of an array (or each character of a string) in turn:
for (const ch of "abc") console.log(ch); // a, b, c
Reading all the input. prompt() gives null when the lines run out, so a while loop can read any number of lines:
let line = prompt();
while (line !== null) {
console.log(line);
line = prompt();
}
Leaving early. break leaves a loop at once. continue skips the rest of this pass and goes on to the next. A loop whose condition never becomes false runs forever: StepVioz stops it after 1000 steps in the visualizer.
Syntax
for (let i = 0; i < 3; i++) { ... }
while (count > 0) { ... }
do { ... } while (again);
for (const item of list) { ... }
Example
The visualizer shows the condition checked on every pass, such as i <= 5 with its real value, and the update changing i at the loop line.
// The 7 times table with a for loop.
const n = 7;
for (let i = 1; i <= 5; i++) {
console.log(`${n} x ${i} = ${n * i}`);
}Line by line
const n = 7fixes which table to print.let i = 1runs once, before anything else.i <= 5is checked. It is true, so the body runs.- The body prints one row, using a template string that does the multiplication inside it.
i++makesi2, and the condition is checked again.- When
ireaches 6, the condition is false and the loop ends.
Expected result
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
In the real world
A loop adds up the prices in a shopping cart, draws each row of a table, checks every field of a form and tries a failed download a few more times. When you open a page that lists search results, a loop built that list from the data.
Common mistakes
- Off by one.
i <= arr.lengthgoes one past the end. Usei < arr.length. - Forgetting the update in a while loop, so the condition never changes.
- Using
for...inon an array. It gives the indexes as strings. Usefor...offor the items. - Changing the loop variable inside the body as well as in the update.
Best practices
- Prefer
for...ofwhen you do not need the index, because it cannot go out of range. - Keep the body short, and move long work into a function.
- Before running a
whileloop, ask what makes it stop.
Summary
for counts, while repeats until a condition fails, and do...while always runs once. for...of visits each item. break leaves the loop and continue skips to the next pass.
Quick check
Key takeaways
- Use for when you can count the passes, and while when you cannot.
- Every loop needs something that moves it towards its end.
- Use for...of to visit the items of a list or the characters of a string.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.