Loops
Programming Languages · JavaScript Functions & Arrays · 14 min
Repeat code without copy-pasting: for, for...of, while, break and running totals.
The for loop
A loop repeats code. The classic for loop has three parts: a start, a keep-going condition, and a step.
for (let i = 0; i < 3; i++) {
console.log(i); // 0, then 1, then 2
}
i++ means "add 1 to i". The loop stops when i < 3 becomes false.
Use a
forloop to print the numbers 1 to 5, one per line.
Looping over an array: for...of
for...of walks through an array one item at a time. No index counting needed.
const pets = ["cat", "dog"];
for (const pet of pets) {
console.log(pet);
}
Each time round, pet holds the next item.
Use
for...ofto printI likefollowed by each snack.
The while loop
A while loop keeps going as long as its condition is true. It's great when you don't know in advance how many rounds you need.
let fuel = 3;
while (fuel > 0) {
console.log(fuel);
fuel--; // subtract 1
}
Always change something inside, or the loop never ends.
Use a
whileloop to count down fromcount(5) to 1.After the loop, print
Liftoff!.
Stopping early with break
break jumps out of a loop straight away, even if there are items left. Use it once you've found what you were looking for.
for (const word of words) {
if (word === "stop") {
break;
}
console.log(word);
}
Loop over
numberswithfor...of. If a number is bigger than 10, printFoundand the number, thenbreak.Otherwise, print the number. Nothing after 12 should print.
A running total
To add up a list, start a variable at 0 before the loop, and add each item to it inside the loop. total += x is short for total = total + x.
let sum = 0;
for (const n of [1, 2, 3]) {
sum += n;
}
console.log(sum); // 6
Create
let total = 0, then loop overpricesand add each one tototal.After the loop, print
total.
Put it together: step tracker
One loop can do two jobs at once. Go through a week of step counts: add every day to a total, and count the days that hit the 8000-step goal.
Loop over
stepsand keep a runningtotal. After the loop, printTotal:and the total.In the same loop, count the days with 8000 steps or more in
goalDays. PrintGoal days:and the count.
More in JavaScript Functions & Arrays
Previous: Arrays · Next: Array Methods