Intro to Arrays

Iterating Arrays

🙋 Need help? Ask an expert now!

Iterating arrays can be accomplished with for loop. The for loop can be used to process an array and to execute specific tasks to the elements. The element is accessed and changed using the loop index (arrayname[index]) inside the loop body. Using a for loop, you can achieve anything with an array, including summing the elements, squaring each element, removing certain elements, etc.

The for-in or for-of loop can also be used to iterate through an array. The biggest benefit of using these loops is that you don't need to know the length of the array. Each element of the array will be accessed and changed accordingly if these loops are used. All the elements are accessed one at a time and are executed with the statements inside the loop body. Another reason why you would use this is to simplify your code and making it more concise.

The first example above iterates through the array using a for loop. This is probably the method you would want to use in the future if you're not uneasy and hesitant about using the for-in or for-of loops. The for loop reads each element of the array and adds it to the variable sum, thus printing the sum of the array. The for-in loop reads each element of the array and prints the values one by one, starting from index 0.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [17, 34, 21, 42, 15, 69, 48, 25, 39];
            for (i = 1; i < arr.length; i = i + 3){
                arr[i] = arr[i - 1] + 3;
            }
            

What numbers will the array contain after the for loop is executed?