Looping through arrays (and strings)

By now you should be familiar with both arrays and for loops. In this tutorial we are going to use both of these coding concepts. We can easily use a for loop to loop through each element in an array.

Watch the video below and then scroll down the page to access the code which you can use yourself.

In the sample code below, we will loop through every member of the Simpsons family and print each family member on a new line. Each family member is an element in simpsonsArray and the arrayLength variable stores the length of the simpsonsArray (the number of elements in the array) as a number value. There are five elements in the array so there will be five iterations of this for loop.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - For Loops</title>
 <script type="text/javascript">
 
 // This example shows how to loop through an array
 var simpsonsArray = ["Homer","Marge","Bart","Lisa","Maggie"]; // this is the array
 var arrayLength = simpsonsArray.length; // this variable stores length of the array (no. of elements in array)
 for (i = 0; i < arrayLength; i++) {
 document.write(simpsonsArray[i],"</br>"); // this will show each family member on a new line
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

We can also loop through every character in a string variable too. The code below loops through every letter in the word variable and displays each letter on a new line.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - For Loops</title>
 <script type="text/javascript">
 
 // This example shows how to loop through each character in a string
 var word = "Hello"; // this is the string variable
 var wordLength = word.length; // we use the length method to store the length of the word string in a variable
 for (i = 0; i < wordLength; i++) {
 document.write(word[i],"</br>"); // this will show each letter of the word on a new line
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Objects, properties and methods