Contents  >

Working with Arrays

Learning Goals

In this Lesson, you will learn how to:

  • Declare an array
  • Populate an array with a series of comma-separated values on a single line
  • Populate an array with a list of values and index numbers on multiple lines.
  • Access the value a particular element in an array
  • Use a for loop to read all the elements of an array
  • Find the length of an array
  • Use the length property of an array as the upper limit of the counter variable in a for loop
  • Add, modify and delete individual array elements

In this Lesson, you will meet the following term:

  • Array

Exercise Files

In this Lesson, you will work with the following HTML files:

Download the compressed file below and copy it to your websites/javascript/exercises sub-folder.

📄   9.zip

Unzip the six files it contains into a sub-folder named /9.

Arrays: When variables are not enough

A variable, as you have learnt, can store a value that may change over time. Think of a variable as a box, in which you can place a single value. At any stage in the script you can change the value in the box. A variable can be declared, and a value assigned to it, in a single statement as shown below.

let userName = “Bridget”;

You can think of this variable as a single-compartment box that contains just one value.

Arrays

But suppose you want to store several values in a box? You need a different kind of box: an array. You can declare and assign several values to an array as follows.

let userNames = new Array ("Bridget","Carol","Christine","Deborah");

The individual array elements are separated by commas. You can also include single blank spaces after the commas as shown below.

let userNames = new Array ("Bridget", "Carol", "Christine", "Deborah");

This array or multi-compartment box has four values.

Arrays

Each array element has an identifying number known as an index. Index values always begin at zero. An array with 4 elements, for example, has the following index values: [0], [1], [2] and [3].

Arrays

You must follow the same rules when naming arrays as you do when naming variables:

  • Do not use the same name for two different arrays within the same web page.
  • Do not insert spaces within array names.
  • To make array names easier to read, you can combine upper and lowercase letters.
  • Be aware that array names are case-sensitive: 'myArray' is not the same as 'myarray'.

Assigning values to the elements of an array is known as populating the array.

Array

A variable that can hold multiple values. Array names follow the same rules as variable names. Each element in an array is identified by an index number, beginning with zero.

The benefit of using arrays is that you can manipulate a large range of values with just a single name and an index number. For example, instead of assigning the twelve months of the year to twelve different variables, you could assign them to a single array.

Exercise 9.1 Creating an array: single line method

In this exercise, you will declare and populate an array using a series of comma-separated values on a single line. This is just one of the two methods of populating an array.

  1. Open the following file in VS Code and your web browser:   📄   exercise-9-1.html
  2. In the empty <script> tag pair, declare a variable named 'authors', create an array with this name, and populate the array with six values as shown below.
    let authors;
    authors = new Array("Goddard","Grisham","Christie","Bryson","Heller","Jerome");    
  3. Save the exercise-9-1.html web page.

A second method of populating an array is to write, on a series of different lines, each element's value and its associated index number. For example.

let userNames = new Array;
userNames[0] = "Bridget";
userNames[1] = "Carol";
userNames[2] = "Christine";
userNames[3] = "Deborah";

The two approaches produce the same result.

  • Single line method: For two or more arrays, one positioned beneath the other, the single-line method makes it easier to compare the different sets of array elements. An example is shown below.
    let fNames = new Array("John","Kylie","Elton","Dianna");
    let sNames = new Array("Lennon","Minogue","John","Ross");
  • Multi-line method: For a single array with a large number of elements, the multi-line method makes it easier to read which element is located at which index value.

Exercise 9.2 Creating an array: multi-line method

In this exercise, you declare and populate an array using the one-element, one-line method.

  1. Open the following file in VS Code and your web browser:   📄   exercise-9-2.html
  2. In the empty <script> tag pair, declare a variable named 'authors', create an array with this name, and populate the array with six values as shown below.
    let authors;
    authors = new Array;
    authors[0] = "Goddard";
    authors[1] = "Grisham";
    authors[2] = "Christie";
    authors[3] = "Bryson";
    authors[4] = "Heller";
    authors[5] = "Jerome";
  3. Save the exercise-9-2.html web page.

Reading values from an array

Now you know how to populate an array. But how do you read what’s stored in an array? There are two situations when you want to access or ‘get at’ array values:

  • When you want to write the values to the browser window, perhaps with a document.write() statement.   The following example writes the 34th index value from the array named ‘email_addr’ to the browser window.
      document.write(“Email Address: "+email_addr[34]+"<br>");
    
  • To copy an element's value to variable, use an assignment statement such as the one shown below.
      let customer21_id = customer_ids[21];
    
    In the above example, the value of the 21st element in the array named 'customer_ids' is copied to the variable named 'customer_21'. The array remains unchanged.   Copying values from one array another to another is easy. Just use an assignment statement similar to the one below.
      new_films[46] = old_films[187];
    
    In this example, the value of the 187th element in the array named 'old_films' is copied to the 46th element of the array named 'new_films'.

Reading array values with loops

Suppose your script contains an array named ‘fruit’ with six elements. You could write the values of the array’s six elements to the browser window with six separate document.write() statements as shown below.

document.write("Array Element 0: "+fruit[0]+"<br>");
document.write("Array Element 1: "+fruit[1]+"<br>");
document.write("Array Element 2: "+fruit[2]+"<br>");
document.write("Array Element 3: "+fruit[3]+"<br>");
document.write("Array Element 4: "+fruit[4]+"<br>");
document.write("Array Element 5: "+fruit[5]+"<br>");

That's a lot of typing.

There is an easier way: use a for loop containing a single document.write() statement as shown below.

for (i = 0; i <= 5; i++) {
   document.write("Array Element "+i+": "+fruit[i]+"<br>");
}

As you can see, there are six elements in the array. However, the initial value of the counter variable is set to 0 and the upper value is set to 5.

This is because the array's index numbering runs from [0] to [5] and not from [1] to [6].

The array length property

To use a for loop to access all the values from an array, follow this simple rule:

The number of loop iterations must be the same as the number of elements in the array.

That way a document.write() statement is performed for each individual array element.

But the number of array elements may change during the script, so how can you set the upper value for the counter variable?

The solution is to use the length property of the array. This is the index number of the next empty element after highest occupied element in the array.

The following statement assigns the length of the array named ‘towns’ to a variable called 'myVar'.

myVar = towns.length;

You can use an array length property as the upper limit of a for loop as follows.

for (i=0; i < fruit.length; i++) {
   document.write(“Array element "+i+:"" fruit[i];
}

Notice that the comparison operator for the upper value of the counter variable is 'less than' (<) and not 'less than or equal to' (<=).

Why?

Because the array length is always one greater than the index number of the highest array element.

For example, When an array has six elements, its index numbers run from [0] to [5], and its length property contains the value of 6.

Exercise 9.3 Reading array values with a for Loop

In this exercise, you will use a for loop to write the elements of an array to a HTML table in a web browser window.

  1. Open the following file in VS Code and your web browser:   📄   exercise-9-3.html
  2. You can see the array that you created and populated with six values from Exercise 9.2.
  3. Beneath the final array population statement, add a single document.write() statement as shown below.
    document.write(authors[0]");
  4. Save the HTML file and view it in your web browser. You should see the content of the first value in the array ("Goddard"). Arrays
  5. Next, rplace your single document.write() statement with a for loop as follows.
    for ( i = 0; i <= 5; i++ ) {
        document.write("<p>"+authors[i]+"<\/p>");
    }
  6. Save the HTML file and view it in your web browser. It should now look as shown below. Arrays

All done. You can close the exercise-9-3.html web page when finished.

Assigning, modifying and deleting array values

Up to now, you have populated array elements only at the time you created the array. But you can insert values into an array at any stage. The general syntax is as follows.

array_name[index_number] = element_value;

The following code assigns the number 34 to the 20th index position of the array named myArray.

myArray[20] = 34;

You don't need to populate array elements in consecutive order, as in [0], [1], [2], [3], [4] and so on.

Imagine that you have an array called 'userNames'. It contains 10 elements, indexed from [0] to [9]. The following three statements are all valid.

userNames[10] = "Murphy";
userNames[11] = "Jones";
userNames[20] = "Collins";

In other words, JavaScript allows you to have 'gaps' or unfilled elements in an array. An array with such non-contiguous values is said to be sparsely populated. JavaScript treats the value of an unfilled array element as undefined.

Modifying array values

You change the value of an array element in exactly the same way as you first assign a value to that element. If your 'userNames' array currently has values at index locations [8], [9] and [56], the following statements overwrite those values with the new ones.

userNames[8] = "Harper";
userNames[9] = "Wallace";
userNames[56] = "Johnson";

Deleting array values

You can remove the contents of an array element with the delete method.

delete userNames[67];

This does not actually delete the element from the array; it just sets its value as undefined. The length property of the array is unaffected.

Uploading your JavaScript exercise files to GitHub

Follow these steps below to upload your entire 📁 /javascript sub-folder to your website on GitHub.

  1. Sign in to Github and click the name of the repository (‘repo’) that holds your web pages.
  2. On the next GitHub screen displayed, click the Add file button near the right of the screen and then choose Upload files from the dropdown list. github-upload-portfolio
  3. In File Explorer (Windows 10) or Finder (Apple Mac), select your entire 📁 /javascript sub-folder, and drag-and-drop it to your repository on GitHub. Introduction to Images
  4. Scroll down to the bottom of the GitHub screen, and accept or edit the short message (Add files via upload) in the Commit changes box.   Finally, click the green Commit changes button to upload your entire 📁 /javascript sub-folder and all the exercise files it contains.

Your uploaded files are published on GitHub at a web address similar to the following, where username is the username you have chosen for your GitHub account:

https://username.github.io/javascript/exercises/9/exercise-9-1.html
https://username.github.io/javascript/exercises/9/exercise-9-2.html
https://username.github.io/javascript/exercises/9/exercise-9-3.html

It may take a few minutes for your uploaded files to appear on GitHub.

Lesson Summary

An array is a type of variable that can hold multiple values. Each element in an array is identified by an index number, beginning with zero. You can declare and assign several values to an array as follows.

let userNames = new Array ("Bridget","Carol","Christine","Deborah");

The individual array elements are separated by commas. A second method of declaring and populating (assigning values to) an array is to write, on a series of different lines, each element’s value and its associated index number. For example.

let userNames = new Array;
userNames[0] = "Bridget";
userNames[1] = "Carol";
userNames[2] = "Christine";
userNames[3] = "Deborah";

You can write a value from an array element to the browser window with a statement such as the following.

document.write("Email Address: "+email_addr[34]+"<br>");

To assign an element’s value to a variable, use an assignment statement such as the one shown below.

let customer21_id = customer_ids[21];

Copying values from one array another to another is easy. Just use an assignment statement similar to the one below.

new_films[46] = old_films[187];

You can read all values from an array using a for loop such as that shown below.

for (i=0; i <=5; i++)
   document.write("Array Element "+i+": "+fruit[i]+"<br>");

You can use the length property of the array object as the upper value of the loop counter variable. This is the index number of the next empty element after highest non-empty element in the array as follows.

for (i=0; i < fruit.length; i++)
   document.write("Array element "+i+:" fruit[i];

Notice that the comparison operator for the upper value of the counter variable is ‘less than’ (<) and not ‘less than or equal to’ (<=).

This is because the array length is always one greater than the index number of the highest array element. When an array has six elements, its index numbers run from [0] to [5], and its length property contains the value of 6.

You don’t need to populate array elements in consecutive order. JavaScript allows you to have ‘gaps’ or unfilled elements in an array. An array with such non-contiguous values is said to be sparsely populated. The value of an unfilled array element is ‘undefined’. You can remove the contents of an individual array element with the delete method.

delete userNames[67];

This does not actually delete the element from the array; it just sets its value as ‘undefined’. The length of the array in unaffected.


Return to Contents.