Register to get access to free programming courses with interactive exercises

Traversing a string in a loop JavaScript fundamentals

You can use loops to process strings as well as numbers. Mainly as a method for retrieving a specific character by its index. Below is an example of code that prints each letter of a word on a single line:

const printNameBySymbol = (name) => {
  let i = 0;
  // This test works until a string ends,
  // including the last character. The last index is `length - 1`
  while (i < name.length) {
    // Get a character by its index
    console.log(name[i]);
    i = i + 1;
  }
};

const name = 'Arya';
printNameBySymbol(name);
// => 'A'
// => 'r'
// => 'y'
// => 'a'

The right test condition for the while loop is essential in this code. You can do it two ways: i < name.length or i <= name.length - 1. Both lead to the same result.

Building strings with loops

Loops also allow you to generate strings. It's a common task for web development. It's merely basic aggregation using interpolation or concatenation.

One especially popular task among interviewers is to do a string reversal. There are lots of ways to solve it, but the most basic is by iterating each character. Have a look at how this function works:

reverse('Hexlet'); // telxeH

The general idea of the reversal is that you take characters one by one from the beginning of the string and then connect them in reverse order. Sounds like a piece of cake. Now let's examine it:

const reverse = (str) => {
  let i = 0;
  // A neutral element in terms of strings is an empty string
  let result = '';
  while (i < str.length) {
    // Connect it in reverse order
    result = `${str[i]}${result}`;
    // Same through concatenation
    // result = str[i] + result;
    i = i + 1;
  }

  return result;
};

const name = 'Bran';
reverse(name); // 'narB'
// Testing neutral element
reverse(''); // ''

Perhaps the only tricky part here is getting a feel of how the string itself is built. Since each next character is attached to the resulting string on the left, the string ends up reversed.

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY