Essential JavaScript

Looping Over Strings

Loops give us a way to act on each individual character in a string.

We can loop over a string by keeping track of the index of the current character we are working with.

Each time the loop runs, we bump the index up by one. We stop once index reaches the string's length value, which means we hit the end of the string.

const myString = 'surprise';
let index = 0;
while (index < myString.length) {
  let letter = myString[index];
  console.log(letter);
  index++;
}

We could also work backwards through a string if we wanted:

const myString = 'surprise';
let index = myString.length - 1;
while (index >= 0) {
  let letter = myString[index];
  console.log(letter);
  index--;
}

Learning Goals

Code Editor