6.3: Loops with Arrays

Learning Objectives

By the end of this lesson, you should be able to:

  • Use the built-in .length array property.

  • Use either a while or for loop to access or manipulate elements of an arbitrary-length array.

Introduction

Often we want to perform actions on all elements of arrays of arbitrary length. We can use loops to run code on each array element sequentially.

The trick to using loops with arrays is to link the counter loop concept with the index array concept. Typically, the counter represents the current index of the array, and the length of the array is the maximum counter value plus 1. The "plus 1" is because array indexes are 0-indexed, thus the maximum valid array index is the array length minus 1.

Looping Over Arrays

To get the length of an array, we can use the .length method. This method exists on every array.

In the following example we use letters.length to determine the number of loop iterations. We use index to access each element in the array sequentially, 1 element per loop iteration.

Address Book Example

Let's create a practical example of loops with arrays using an address book. Our address book stores unique names in an array, i.e. will not add a name if it is already in the book.

Exercises

Follow Along

Implement the above code.

Last updated