Arrays



index
Disabled back button Next Section
printable version

Section 1: Introduction

Without arrays, it is cumbersome to set up a list of related variables....

var president01 = "George Washington";
var president02 = "John Adams";
var president03 = "Thomas Jefferson";
var president04 = "James Madison";
var president05 = "James Monroe";
var president06 = "John Quincy Adams";
var president07 = "Andrew Jackson";
var president08 = "Martin Van Buren";
var president09 = "William H. Harrison";
var president10 = "John Tyler";

Using individual variables requires ten different output statements, or forty-plus if you list all presidents:

var outputString="";
outputString += president01 +"\n";
outputString += president02 +"\n";
outputString += president03 +"\n";
outputString += president04 +"\n";
outputString += president05 +"\n";
outputString += president06 +"\n";
outputString += president07 +"\n";
outputString += president08 +"\n";
outputString += president09 +"\n";
outputString += president10 +"\n";
alert(outputString);

array demo

An array is an enumerated list of variables. It is a programming construct that allows programmers to replace the above code with this:

var presidentArray = ["George Washington", "John Adams", "Thomas Jefferson",
         "James Madison", "James Monroe", "John Quincy Adams",
         "Andrew Jackson", "Martin Van Buren", "William H. Harrison",
         "John Tyler" ];

var outputString="";
var len = presidentArray.length;
for (var presCtr = 0; presCtr < len; presCtr ++)
{
   outputString += presidentArray[presCtr] + "\n";
}
alert(outputString);

Array demo

The index (the number in the square brackets) can be a variable, allowing for easy looping through the data structure no matter how many presidents you included.

Definition

array demo 2

Justification

Another Example Situation

Section 2: Declaration

There are multiple ways in which to declare an array.

Example:

var myArray = [];

You do not have to specify an array size.

You can also declare an array like this:

var array_name = new Array();

Example:

var myArray1 = new Array();

var myArray2 = new Array(100);

Link: Literal notation

Section 3: Initialization

As demonstrated above, you can specify an initializer list (between the square brackets) when you declare the array.

You can also initialize array elements individually after an empty array has been declared:

var numberList = [];

numberList[0] = 1;
numberList[1] = 2;
numberList[2] = 3;
numberList[3] = 6;

You can store anything in a JavaScript array; the data does not even have to be the same type.

var myArray = [ 3, 'hello', function() {return 5}, true];

Section 4: Accessing array elements

To access a particular element in an array, use the array name and an index.

array_name[constant or variable]

The index can be a variable, constant, or expression that should evaluate to an integer value, and indicates the location of the element that will be referenced.

array access

Example

var gradeList = [];
gradeList[0] = 98;

Array gradeList is an expandable group of memory locations.

array representation

gradeList[0] refers to the first element in the group.

gradeList[i-1] refers to the ith element in the group.

The index must evaluate to integer greater than or equal to 0 and less than the length property.

Section 5: Processing arrays

The array length property contains the number of elements in the array.

To process the entire grade list element-by-element, you can use a for loop.

var outputString="";
for (var ctr = 0; ctr < gradeList.length; ctr++)
{
   outputString += gradeList[ctr] + "\n";
}
alert (outputString);

If an application requires either processing all elements in the array or stopping if a certain condition is detected, a while loop must be used.

The following example checks all students in a class to determine whether everyone is passing.

var allPassing = true;
var ctr = 0;
while ((ctr < gradeList.length) && allPassing)
{
   if (gradeList[ctr] < 60)
   {
      allPassing = false;
   }
   else
   {
      ctr = ctr + 1;
   }
}

Section 6: Example

var studentGrade = ["F", "B", "C", "A", "F", "C", "A", "A", "C", "B" ];

Example array

The statement

studentGrade[4] = "F";

...assigns "F" to the fifth cell in the array studentGrade (again).

The statements

var ID = 6;
studentGrade[ID] = "A";

...again assigns "A" to the seventh cell in the array studentGrade.

The loop

var outputString="";
for (var ID = 0; ID < studentGrade.length; ID++)
{
   outputString += studentGrade[ID] + " ";
}
alert (outputString);

...prints all the values in studentGrade: FBCAFCAACB

The loop

var outputString="";
for (var ID = 0; ID < studentGrade.length; ID++)
{
   outputString += "Student " + (ID+1) + "Grade " + studentGrade[ID] + "\n";
}
alert (outputString);

...prints all the values in studentGrade in a more readable form.

Student 1 Grade F
Student 2 Grade B
:
:
Student 10 Grade B

JavaScript is also capable of processing an entire array at once.

Section 7: Adding elements to the end of an array

There are various ways to add an element to next available location in an array, but the easiest is to use the Array.length property.

myArray[myArray.length] = 'new stuff'; // Adds item to end of Array

Section 8: Bounds checking

If an attempt is made to access an element outside of the array bounds, it is a run-time error. i.e., JavaScript performs bounds checking on array subscripts.

For example, given the declaration

var studentGrade = ["F", "B", "C", "A", "F", "C", "A", "A", "C", "B" ];

a loop like the following

var outputString="";
for (var ID = 0; ID <= studentGrade.length; ID++)
{
   outputString += studentGrade[ID] + "\n";
}
alert (outputString);

...will result in an error because the indexes run from 0 to 9 but the loop runs from 0 to 10, and the attempt to access studentGrade[ID] when ID has a value of 10 would be a run-time error.

Section 9: Examples using arrays

Link

Section 10: Array assignment

Assigning an array to a new variable creates a pointer to the original array (see figures below).

If you then create a new variable and try to copy the new array to it, as follows...

var newArray = numArray;

...it causes this to happen:

numArray copy

Notice that there is only one array, but now it has two names.

Printing the contents of that array element associated with either name produces the same results:

alert(numArray[1]); // outputs 'new'
alert(newArray[1]); // outputs 'new'


You can make a separate copy of an array in another array variable, but you have to do it manually or use Array.slice().

var numArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var newArray = numArray.slice();

produces this...

array copy 4

More on Array.slice() in the discussion of array functions (see link at end of notes).


Manual copy:

var numArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var newArray = [];

for (var ctr = 0; ctr < numArray.length; ctr++)
{
   newArray[ctr] = numArray[ctr];
}

produces this...

array copy 4

But this time the assignment statement

newArray[1] = 'new';

...changes only one array.

array copy 5
Section 11: Array methods

Link

Section 12: Extra Info: Two-Dimensional Arrays (Reference Only)

Two-Dimensional Array Notes