Skip to content
Codewilds

Lesson 6 of 34 · Fundamentals

JavaScript Loops: for and while

medium20 XP3 min readFree lesson

Computers are brilliant at doing the same thing over and over without getting bored. Loops let you repeat a block of code: count to a hundred, check every letter of a word, or keep going until a goal is reached.

JavaScript has several kinds of loops. The two you'll use most are the for loop and the while loop.

The for loop

Use for when you know how many times to repeat:

for (let i = 1; i <= 3; i++) {
  console.log(`Round ${i}`);
}
// Round 1
// Round 2
// Round 3

The parentheses hold three parts, separated by semicolons:

  1. Initialisation, let i = 1, runs once before the loop starts.
  2. Condition, i <= 3, is checked before every round. The loop stops when it's false.
  3. Update, i++ (short for i = i + 1), runs after every round.

You can count down or take bigger steps, too:

for (let i = 10; i > 0; i -= 3) {
  console.log(i); // 10, 7, 4, 1
}

The accumulator pattern

A very common job for a loop is building up a result. Start with an empty value before the loop, then update it inside:

let total = 0;
for (let i = 1; i <= 4; i++) {
  total += i;
}
console.log(total); // 10 (1 + 2 + 3 + 4)

Looping over a string

Strings have a length and indexes, so a for loop can visit every character:

const word = "orc";
for (let i = 0; i < word.length; i++) {
  console.log(word[i]); // o, r, c
}

Notice i < word.length, not <=: the last index is length - 1. When you only need the characters and not their positions, the for...of loop is shorter:

for (const char of "orc") {
  console.log(char); // o, r, c
}

You'll use for...of a lot with arrays in Chapter 3.

The while loop

Use while when you don't know in advance how many rounds you need. You only know when to stop:

let hp = 10;
let hits = 0;

while (hp > 0) {
  hp -= 3;
  hits++;
}

console.log(hits); // 4

The condition is checked before each round. If it's false right away, the body never runs at all. Make sure something inside the loop eventually makes the condition false, or the loop runs forever.

break and continue

  • break exits the loop immediately.
  • continue skips the rest of the current round and jumps to the next one.
for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue; // skip even numbers
  if (i > 7) break;          // stop completely after 7
  console.log(i);            // 1, 3, 5, 7
}

Common mistakes

  • Off-by-one errors. i <= word.length goes one step too far and reads undefined. Think carefully about < versus <=.
  • Infinite loops. Forgetting to update the variable in a while loop means the condition never becomes false. Here, the runner stops your code after a few seconds; in a real browser tab, the page freezes.
  • const for the counter. for (const i = 0; i < 3; i++) throws a TypeError, because i++ reassigns i. Use let. (In for...of, const is fine because each round gets a fresh variable.)

Assignment

Complete three functions:

  1. sumTo(n) returns the sum of all whole numbers from 1 to n. Example: sumTo(5) returns 15 (1 + 2 + 3 + 4 + 5). sumTo(0) returns 0.
  2. countVowels(text) returns how many vowels (a, e, i, o, u) the text contains, ignoring upper/lower case. Example: countVowels("Scriptoria") returns 4.
  3. doublingDays(start, target): a slime colony starts with start slimes and doubles every day. Return how many days it takes until there are at least target slimes. Example: doublingDays(1, 10) returns 4 (1 → 2 → 4 → 8 → 16). If start is already at least target, return 0. You can assume start is at least 1.

Loops in other languages

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+20 XP

Press Run to execute your code, or Submit to check it against the tests.