Looping through elements in an array and characters in a string

Coding with JavaScript

🕑 This lesson will take about 10 minutes

If you have been following the previous lessons, you should now be familiar with both arrays and for loops. In this lesson, we are going to use both of these coding concepts. We can use a for loop to work through each element in an array. We can also use for loops to work through each individual character in a string value.

How does it work?

  • Remember that each element in an array has an index that represents its position in the array. Indexing starts from 0. For example, the first element has an index of 0, the second element has an index of 1, the third element has an index of 2, and so on.

  • Characters in a string are also indexed, just like an array. For example, in the string “Hello world”, the first character “H” has an index of 0, “e”, has an index of 1, and so on.

  • When we want to access a specific element in an array (or character in a string), we can reference the element’s index in square brackets [ ] after the array or string variable’s name. For example, to access an element with an index of 2 in an array called myArray, we would write myArray[2];

  • For loops have a built-in counter (usually called i) that can start counting from 0 and increasing by 1 in each iteration (repetition) of the loop

  • This means that we can use the counter in the loop to access each element in an array (or character in a string), one by one. For example, in the first iteration of the loop, we can access element 0, in the second iteration of the loop we can access element 1, and so on.

  • So, in a for loop, if we wish to access each individual array element one by one, we can use the counter variable i to represent the index of the elements in the array we wish to index eg. myArray[i] - each time the loop repeats, i increases, which means we can access the next element with a higher index.

For loops can be useful for searching for a particular element in an array or a character in a string, and for processing elements in arrays and characters in strings (eg. replacing or modifying values).

Watch the video below and then scroll down the page to view the sample code.

Sample HTML and JavaScript code

Next lesson: forEach loops