Loops — JavaScript

for (let i = 1; i <= n; i++) { ... } repeats code with a counter i: a starting value, a condition checked before every pass, that is, every run of the code…

You're asked to print the numbers 1 to 100. You could write console.log a hundred times, but that is tiring. And if you then have to go up to 1000, you write 900 more lines. Adding up every price in a shopping cart can't be written line by line either, because every person has a different number of items.

A loop runs the same code many times, without you writing it again. Each time the loop's code runs is called one pass (an iteration).

The for loop

This for loop prints three lines:

for (let i = 1; i <= 3; i++) {
  console.log("Iteration " + i);
}
// Iteration 1
// Iteration 2
// Iteration 3

Inside the parentheses of for there are three parts, separated by semicolons:

After the third pass, i becomes 4. 4 <= 3 is false, so the loop stops.

Many loops start at 0 and use <. for (let i = 0; i < 3; i++) runs for i = 0, 1, 2, so three passes. Use <= when the boundary number (here 3) should be included, and < when it shouldn't.

The while loop

This while loop prints the same three lines:

let i = 1;
while (i <= 3) {
  console.log("Iteration " + i);
  i++;
}

while only has a condition inside its parentheses. So the counter i is made before the loop, and increased inside the loop with i++. If you forget to write i++, the condition is always true. The loop never stops, and the page freezes.

Collecting results in a loop

This example uses a loop to fill an array and add up a total:

const results = [];
let total = 0;

for (let i = 1; i <= 4; i++) {
  results.push(i * 10);
  total += i;
}

console.log(results); // [10, 20, 30, 40]
console.log(total); // 10

Inside a function, return also goes after the loop. If you write return inside the loop, the function stops on the first pass.

for...of: an array's items one by one

for...of loops over the items of an array:

const fruits = ["apple", "orange", "mango"];

for (const item of fruits) {
  console.log(item);
}
// apple
// orange
// mango

On every pass, item holds one item of the array, from the first to the last. You need no counter. There is also for...in, but on an array for...in gives you the index (the position number of each item, starting at 0) as text ("0", "1", "2"), not the value.

Choosing a loop. Which loop for which job:

Loop When to use it
for...of The usual choice for arrays: it takes each item in turn, with no counter.
for You need the number of the pass, or the number of passes is fixed, such as 1 to 100.
while You do not know the number of passes yet, such as "repeat while the balance is still enough".

break and continue

These two keywords change how a loop runs, from inside it. (An if can be written without { } when it holds only one instruction.)

for (let i = 1; i <= 5; i++) {
  if (i === 2) continue;
  if (i === 4) break;
  console.log(i);
}
// 1
// 3

⚠️ Why does my loop throw an error or give NaN?

TL;DR: for (let i = 1; i <= n; i++) { ... } repeats code with a counter i: a starting value, a condition checked before every pass, that is, every run of the code inside, then add one at the end of the pass. A loop that starts at 0 with the condition i < 3 runs 3 times, while <= includes the boundary number. while (condition) repeats as long as the condition is true, so don't forget to change the counter inside the loop. Collect results in an empty array with push, or in a total that starts at 0, then write return after the loop. for...of gives you the value of each item in an array, one by one. continue skips one pass, and break stops the loop.

⚡ Start, condition, add one

Write:

for (let i = 1; i <= 3; i++) {
  console.log("Iteration " + i);
}
Guess first: how many times does for (let i = 0; i < 3; i++) run?

Three times, for i = 0, 1, 2. When i becomes 3, i < 3 is false and the loop stops. Use <= when the boundary number (here 3) should be included, and < when it shouldn't.

Meaning: A for loop repeats the code inside { }. One run is called one pass. let i = 1 runs once at the start and makes the counter i. i <= 3 is the condition, checked before every pass: as soon as it is false, the loop stops. i++ adds 1 to i at the end of every pass.

⚡ Collect the results

Write:

let total = 0;

for (let i = 1; i <= 4; i++) {
  total += i;
}

console.log(total); // 10

Meaning: total += i is the same as total = total + i: on every pass, the value of i is added to total. Start total at 0, because a total with no starting value gives NaN (not a number). Inside a function, return goes after the loop, not inside it, so that the loop can finish.

⚡ for...of: the values directly

Write:

const fruits = ["apple", "orange", "mango"];

for (const item of fruits) {
  console.log(item);
}
Guess first: if of becomes in, what gets printed?

"0", "1", "2". On an array, for...in gives you the index (the position number of each item, starting at 0) as text, not the value.

Meaning: for...of loops over the items of an array. On every pass, item holds one item of the array, from the first to the last. You need no counter.

What you will learn