Looping Over Strings

Grade 5, page 7 of 11. A two-minute read.

Remember that strings have a length and each character has an index, starting from 0? That makes them perfect for looping:

JavaScript
const word = "HELLO";

for (let i = 0; i < word.length; i++) {
  console.log(`Index ${i}: ${word[i]}`);
}

It prints

Index 0: H
Index 1: E
Index 2: L
Index 3: L
Index 4: O

Notice two important details: we start at i = 0 (the first index), and we use i < word.length, not <=. The word has 5 letters, so the indexes go from 0 to 4. If we used <=, we'd try to read index 5, which doesn't exist.

Counting vowels

Let's count how many vowels are in a sentence:

JavaScript
const sentence = "JavaScript is awesome";
let vowelCount = 0;

for (let i = 0; i < sentence.length; i++) {
  const letter = sentence[i].toLowerCase();
  if ("aeiou".includes(letter)) {
    vowelCount++;
  }
}

console.log(`"${sentence}" has ${vowelCount} vowels.`);

It prints

"JavaScript is awesome" has 8 vowels.

That "aeiou".includes(letter) is a neat trick: instead of writing letter === "a" || letter === "e" || ..., we just ask whether the letter appears in a string of all the vowels.

Reversing a string

JavaScript
const original = "stressed";
let reversed = "";

for (let i = original.length - 1; i >= 0; i--) {
  reversed += original[i];
}

console.log(reversed);

It prints

desserts

We start at the last index (length - 1) and count down to 0, adding each letter to a new string. "stressed" backwards is "desserts," which is an excellent life lesson.

The for...of loop

When you just want each character and don't care about the index, there's a cleaner loop called for...of:

JavaScript
for (const letter of "WOW") {
  console.log(letter);
}

It prints

W
O
W

No counter, no length, no square brackets. Just "for each letter of this string, do this." You'll see a lot more of for...of in Grade 7, when we loop over lists.

Watch outOff-by-one errors

Starting at 1 instead of 0, or using <= instead of <, are such common mistakes that they have their own name: off-by-one errors. If your loop runs one time too many or one time too few, or you see undefined at the end of your output, check your start value and your condition. There's an old joke: "There are two hard problems in programming: naming things, cache invalidation, and off-by-one errors."

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning