Using Loops in JavaScript

Iterate over the contents of a String or Array

Using Loops in JavaScript

Photo by Jason Leung on Unsplash

In previous articles we have talked about how for, while, and do...while loops work at a basic level. So I hope that you have taken some time and played around with those loops enough that you feel comfortable enough to take on todays examples.

So let's talk a bit about what else can we do with loops? What makes them such a powerful and versatile tool in our development arsenal?

Let's explore a few common things that you may not think about originally when you first start your study of programming. You will quickly learn that we use one, or a variety of these methods, depending on the task that we want to accomplish. Remember that you're not just a JavaScript developer, you are a PROBLEM SOLVER!! JavaScript just happens to be the tool we are learning at the moment. Keep learning and you will have other tools like Python, Java, C, Go, and a dozen other programming languages to solve whatever the problem you encounter is.

I ramble... I know. Onward!

Iterate through a String

As humans we can read through a piece of text without thinking about it much, so something like checking if a word (type String in our code) has a special character or a number as part of it is pretty easy.

let example1 = "sev7en";
let example2 = "womb@t";

How easy is it for your computer to do the same task? I guess that is kind of a trick question because the question should be, how easy do you think it is for you to program the computer to do this task? I know, heavy, right? Let's try and lighten that mental load and see how we start with "looping" through each character in the string, then we can add additional code so we can find the character that doesn't belong and deal with it accordingly.

So how do we loop through a string?

There are several ways that this can be accomplished in JavaScript. Let's start with how we might use a for() loop to accomplish this task.

let testString = "sev7en";

for(let i = 0; i < testString.length; i++) {
     console.log(testString[i]);

     // code to find character that doesn't belong
}

/* Output -> "s"
             "e"
             "v"
             "7"
             "e"
             "n"
*/

What is happening in the code above? First we define the testing string, then we use a for() loop to iterate through the string. In the for() loop we initialize the iterator "i" to zero so we start at the beginning of the string. Fortunately for us, in JavaScript, Strings act very similar to Arrays. In this case, the length of the String would be the similar to the length or number of items in an Array. Arrays start where? At index ZERO. We just talked about the length of the string, which is the testing condition of our loop. Finally, to round out the loop definition, we increment the iterator "i" by one after the final statement within the loop. But what is happening inside the loop? We are running a console.log() on the variable testString.

But... what is that [i] thing on the end?

As we said Strings act like Arrays when we are looping through their contents. So we have an iterator that increases in value each time through the loop. By using the iterator we can peak into the THING (String, Array, Set, Object) because we have the ability to look at the ITEM, or character at each INDEX. This is where the testString[i] part comes in. The first iteration through the loop "i" is zero so we are looking at the character at index zero, console.log(testString[0]); // Output -> "s". We increment our iterator "i" and now i = 1. Take a look at the value at index one, console.log(testString[1]); // Output -> "e". This continues until our iterator increases to a value of 6, at which point the testing condition no longer evaluates to TRUE (i is 6 < testString.length is 6 : 6 < 6 -> FALSE) and we exit the loop and continue on with the rest of the code in the application.

Now we are looping through the contents, basically looking at each character, of the string. Any code that we want to add to check character type, equivalent value, or to filter data can be added within the for() loop. But thats for another article.

The for() loop is not the only method that we can use to achieve these results. We also can use a for...of loop to peak into the context/value at each position in the string under task.

Iterate through an Array

We can use a for() loop to do the same thing in an Array just as we did with a String. Let's take a quick look before we move on to another type of loop.

let strArr = ["s", "e", "v", "e", "n"];

for(let i = 0; i < strArr.length; i++) {
     console.log(strArr[i]);
}

/* Output -> "s"
             "e"
             "v"
             "e"
             "n"
*/

This all works just like looping through a string. Cool right? This is one tool that we can use on multiple types of Objects in JavaScript.

How about another tool we can use to loop through an Array? The for...of loop. The for..of loop in JavaScript allows you to iterate over iterable objects (arrays, sets, maps, strings, etc) without the need of a counter variable.

Syntax of the for...of loop:

for (element of iterable) {
    // body of for...of
}

This one is nice and easy to understand; for every element in the iterable, execute the code in the loop. The element represents the item contained within the iterable object during each iteration through the loop. The iterable can be any type of iterable object, such as Strings, an Array, Set, Map, etc.

I like examples, so let's see this in action:

let shoppingList = ["apples", "coffee", "milk", "eggs", "cheese"];

for(item of shoppingList) {
      console.log(item);
}

/* Output -> apples
             coffee
             milk
             eggs
             cheese
*/

First, we define our shopping list with 5 items in an array. We enter the for...of loop and in this case the variable we define as "item" (As you saw above, it was defined as "element." This can be called anything you want, as long as we continue to use the same variable name throughout the loop.) represents the value of each item/element at the current iteration through the loop.

forEach() loop:

Let's learn another method we can use to loop through an array. This time we are taking a look at a method that contains a callback function where we can change, manipulate, modify, or even search through the values within the array and run some code on each item of the array. To put it a little more simply, the forEach() method calls a function for each element in an array.

Syntax forEach() loop:

jsArray.forEach(function(item) {
     console.log(item);
});

In the code above we start with an Array object and run the forEach() method on it. Within the forEach() method we have a callback function where we define a parameter that will represent each item in the array during the current iteration. Within this function we can do the same things we could do within a for() or for...of loop and run code that modifies or prints out the data.

Again, I like examples when I am learning:

let numberArr = [1, 2, 3, 4, 5];

numberArr.forEach(function(number) {
     console.log(number);
});

/* Output -> 1
             2
             3
             4
             5
*/

This follows basically the same type of operation that we have already covered and I think you are getting the idea. Have fun, play around with theses types of loops! Copy the code over into your environment and run them, add items to the loops, or make the examples your own. Like anything that we want to get good at, practice, practice, practice!!!

Hopefully this article on looping through Strings and Arrays in JavaScript was useful to you. Thanks for reading, until next time!