Looping through arrays (and strings)

If you have been following the previous tutorials you should now be familiar with both arrays and for loops. In this tutorial, 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 variable.

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 access the code which you can use yourself.

Below is the sample code from the examples shown in the video.

Sample HTML code:

<html>
    <head>
        <title>Using for loops with arrays and strings</title>
        <script src="script.js"></script>
    </head>
        
    <body>

    </body>
</html>

Sample JavaScript code:

var users = ["Homer", "Marge", "Bart", "Lisa", "Maggie"];

// We can use for loops to work through each element in an array.
// This will go through each user in the users array and display on a separate line in the console.
for(i = 0; i < users.length; i++){
    console.log(users[i]);
}

// This is another method (where x will represent each user in the users array).
for(x of users){
    console.log(x);
}

// Here is an example of using a for loop to search for an element in an array
for(i = 0; i < users.length; i++){
    if(users[i] == "Bart"){
        console.log("I found Bart!");
    }
}

// Here is an example of using a for loop to find an element in an array and modify it
for(i = 0; i < users.length; i++){
    if(users[i] == "Lisa"){
        users[i] = "Lisaaaaa";
    }
}

// We can also use for loops to work through each character in a string.
var word = "simpsons";

// This will display each character in the word variable on a new line in the console.
for(i = 0; i < word.length; i++){
    console.log(word[i]);
}

Next tutorial: forEach loops