Skip to content

Introduction to Arrays

So far, we have had small amount of variables in our program.

This is manageable.

Limited Variables

But, what if we need more? A lot more.

This is not manageable.

Lots of Variables

Or, what if we don't know how many variables we need?

Is this even possible?

Unknown Variable Count

Remember this?

53711: Males: 5 Females: 2
53712: Males: 9 Females: 9
53713: Males: 11 Females: 3
53714: Males: 4 Females: 6
53716: Males: 1 Females: 0

Total Males: 30
Total Females: 20

In order to do this program we needed a lot of variables!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
let zip53711Males;
let zip53711Females;
let zip53712Males;
let zip53712Females;
let zip53713Males;
let zip53713Females;
let zip53714Males;
let zip53714Females;
let zip53716Males;
let zip53716Females;

zip53711Males = 0;
zip53711Females = 0;
zip53712Males = 0;
zip53712Females = 0;
zip53713Males = 0;
zip53713Females = 0;
zip53714Males = 0;
zip53714Females = 0;
zip53716Males = 0;
zip53716Females = 0;

What would happen if the zip codes changed? If more where added or removed?

What would happen if we got a very large file and we didn't know what zip codes were in the file?

Like one of the project 5 parts! 😉

We need a more flexible data storage system!


Creating an Array

All modern programming languages have ways to store data in variables that are flexible, adaptable, easy to use, and very similar to every other programming language. The first of these storage systems we are going to learn is called Arrays.

Here is an array of zip codes. The code is creating a variable and assigning an empty array to it.

1
2
3
// An Array
let zipCodes;
zipCodes = [];
  • We use a set of square brackets [] to make the array. There are no spaces between the brackets.

  • What does this really create? Well, an Array is an object. You will learn lots more about objects in the coming semesters. For now, think of an Array as a piece of running JavaScript code that lets us add data to it.

  • Unlike a variable, we can store many pieces of data in it - convenient!

Variable vs. Array

Adding items to an array

Let's make an array to hold student numbers.

1
let studentNumbers = [];

At this point, the array is empty. We have a few ways of adding items (elements) to an array. Here's is one method. Arrays are indexed by numbers that start at zero. The first slot is named studentNumbers[0].

1
2
// Assign the first element
studentNumbers[0] = 12345;

Let's add another element to the array. We need to use the next slot, which is studentNumbers[1].

1
2
// Assign the second element
studentNumbers[1] = 54321;

All this code together, look like this:

1
2
3
4
5
// Assign two elements
let studentNumbers = [];

studentNumbers[0] = 12345;
studentNumbers[1] = 54321;

We now have two student numbers in our array.

Student Numbers Array

A shortcut

There is a nice way of doing this with less typing. The below code adds the same elements in one line. You could continue adding elements by separating them by commas.

1
studentNumbers[12345, 54321];

Accessing elements in an array

Each individual student number in the array is called an array element. And each element has the same name, studentNumbers. How will we get the individual elements that we need out if they have the same name?

We use the index!

The index of an array starts at zero. This index identifies the location of each element in the array.

1
2
3
4
5
// Print the student numbers

document.write(studentNumbers[0]);
document.write("<br/>");
document.write(studentNumbers[1]);

The Length Property

Remember the length property? We used this property to find the number of characters in a String. We can also use it with an array to get the number of elements stored in the array. It is very useful!

1
2
3
4
5
6
7
8
// Get the length of the arrays
let studentNumbers = [];
let arrayLength;

studentNumbers[0] = 12345;
studentNumbers[1] = 54321;

arrayLength = studentNumbers.length;

In our example array, this would give us 2. The length of an array is ALWAYS one more than the last index. So, the length also gives us the next available index!

Adding elements with the length property

Using the length property we can also add element to an array. This is better than using hard-coded index values because we often don't know what the next available slot is.

1
2
3
4
5
6
7
// Add elements to the array
let studentNumbers = [];

studentNumbers[studentNumbers.length] = 12345; // length is 0 (adding to index 0)
studentNumbers[studentNumbers.length] = 54321; // length is 1 (adding to index 1)
studentNumbers[studentNumbers.length] = 52315; // length is 2 (adding to index 2)
studentNumbers[studentNumbers.length] = 86522; // length is 3 (adding to index 3)

Student Numbers Length


The .push() method

There is one more way to add an element to an array. Since an array is an object, there are methods we can use with it. One of them is the .push() method.

It automatically adds elements to the next available index for us - nifty!

1
2
3
4
5
6
7
// Adding elements with push
let studentNumbers = [];

studentNumbers.push(12345); // adding to index 0
studentNumbers.push(54321); // adding to index 1
studentNumbers.push(52315); // adding to index 2
studentNumbers.push(86522); // adding to index 3

Quick Recap

This 👇 is GOOD stuff, you might want to book mark it

Creating an array

1
let months = [];

Creating array shortcut

1
months = ["January", "February", "March"];

Adding elements

1
2
3
months[0] = "January";
months[1] = "February";
months[2] = "March";

Adding elements with the length property

1
2
3
months[months.length] = "January";
months[months.length] = "February";
months[months.length] = "March";
Adding elements with the .push() method
1
2
3
months.push("January");
months.push("February");
months.push("March");
Accessing elements
1
2
3
4
5
6
// output elements in the array
document.write(months[0]); // January
document.write("<br/>");
document.write(months[1]); // February
document.write("<br/>");
document.write(months[2]); // March


Looping Arrays

Let's start by looking at a complete function. It create an array of area codes and displays them to the page. Does this look any more efficient that using regular variables?

What kind of issues do you see with this code? What would you have to do if we changed, added, or deleted an area code?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
    The first demo function using Arrays.
*/
function createWisconsinAreaCodes() {
    "use strict";

    // Declare our variables
    let areaCodes;
    let output;

    // Create an empty array
    areaCodes = [];

    // Assign six area codes in the array
    areaCodes[0] = 608;
    areaCodes[1] = 414;
    areaCodes[2] = 715;
    areaCodes[3] = 414;
    areaCodes[4] = 262;
    areaCodes[5] = 920;

    // Get the output element
    output = document.getElementById("outputList1");

    // Output each element of the array to the list
    // inside <li> tags.
    output.innerHTML += "<li>" + areaCodes[0] + "</li>";
    output.innerHTML += "<li>" + areaCodes[1] + "</li>";
    output.innerHTML += "<li>" + areaCodes[2] + "</li>";
    output.innerHTML += "<li>" + areaCodes[3] + "</li>";
    output.innerHTML += "<li>" + areaCodes[4] + "</li>";
    output.innerHTML += "<li>" + areaCodes[5] + "</li>";
}
  

    Adding a Loop

    Since the only thing that changes in lines 27-32 in the above version is the value of the index number, we could set this up as a loop!

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    /*
        The second demo function using Arrays.
    */
    function createWisconsinAreaCodesVersionTwo() {
        "use strict";
    
        // Declare our array
        let areaCodes;
        let index;
        let output;
    
        // Create an empty array
        areaCodes = [];
    
        // Assign six area codes in the array
        areaCodes[0] = 608;
        areaCodes[1] = 414;
        areaCodes[2] = 715;
        areaCodes[3] = 414;
        areaCodes[4] = 262;
        areaCodes[5] = 920;
    
        // Get the output element
        output = document.getElementById("outputList2");
    
        // Output each element of the array to the list
        // inside <li> tags.
        for (index = 0; index < areaCodes.length; index++) {
            output.innerHTML += "<li>" + areaCodes[index] + "</li>";
        }
    
    }
    
    
    

      How did that work?

      We took advantage of the length property and the index value to loop through the array. This is more flexible and maintainable.

      Looping thru and Array

      The loop continues until the index is incremented to 7, which will return a false, which stops the loop.


      A Better Version

      We can take advantage of the shortcut of adding elements to an array to remove some lines of code.

      1
      2
      3
      4
      5
      6
      7
      // Assign area codes variables in the array
      areaCodes[0] = 608;
      areaCodes[1] = 414;
      areaCodes[2] = 715;
      areaCodes[3] = 414;
      areaCodes[4] = 262;
      areaCodes[5] = 920;
      

      Reduce to one line. Not only is this smaller, but it's more readable.

      1
      2
      // Assign a whole array with one line of code
      areaCodes = [608,414,715,414,262,920];
      

      Final Version

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      /*
          The third demo function using Arrays.
      */
      function createWisconsinAreaCodesVersionThree() {
          "use strict";
      
          // Declare our array
          let areaCodes;
          let index;
          let output;
      
          // Assign six variables in the array
          areaCodes = [608, 414, 715, 414, 262, 920];
      
          // Get the output element
          output = document.getElementById("outputList3");
      
          // Output each element of the array to the list
          // inside <li> tags.
          for (index = 0; index < areaCodes.length; index += 1) {
              output.innerHTML += "<li>" + areaCodes[index] + "</li>";
          }
      }
      
        
      

        Viewing All Array Elements

        It is possible to display the contents of each and every "slot" of an array as just a comma delimited list. This is fine for debugging, but rarely if ever would this be acceptable as a format to leave in a production program for users to see and have to work with.

         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        /*
            The fourth demo function using Arrays.
        */
        function createWisconsinAreaCodesVersionFour() {
            "use strict";
        
            // Declare our variables
            let areaCodes;
            let output;
        
            // Assign six variables in the array
            areaCodes = [608, 414, 715, 414, 262, 920];
        
            // Get the output element
            output = document.getElementById("outputList4");
        
            // Output the whole array as one <li> tag
            output.innerHTML += "<li>" + areaCodes + "</li>";
        }
        
          
        

          ☝ Notice how this looks just like the data on line 12?


          Array Summary Page

          Helpful "cheat-sheet" for using arrays.


          Labs

          Labs

          1. Lab06: First Arrays
            • unit05/labs/lab-06-arrays.html
          2. Lab07: More Experiments with jsLint
            • unit05/labs/lab-07-jsLint.html

          Exercises

          Exercises

          1. Exercise for Lab06
            • unit05/exercises/exercises-06.html