Arrays

An array is a collection of data. In JavaScript, an ARRAY is also an object.

Think of an array like a chest of drawers. Each drawer in the chest is numbered, and each drawer may contain data, whether that data be a string, a number, a boolean, an object, or another array. You access the data in the "drawers" of an array via the "drawer" number.

Here is a conceptual picture of an array:

Conceptual Drawing of Array

In the above illustration, I have created an array named fred. The array, fred, has four "drawers" or positions, numbered sequentially starting from 0 (array positions always start at 0). In the 0 position (the first drawer) of fred, there is a string, "Hi". In the 1 position (the second drawer) of fred, there is a number, 127. In the 2 position (the third drawer) of fred, there is a boolean value, true. In the 3 position (the fourth drawer) of fred, there is another string, "Wow".

To declare fred in JavaScript, I must instanciate an Array object using the Array() constructor.

Example:

var fred = new Array();

There are several ways that I could then initialize the contents of the positions in fred. The most characteristic means of doing so is by using the ARRAY ACCESS OPERATOR ([]).

Example:

var fred = new Array();
fred[0] = "Hi";
fred[1] = 127;
fred[2] = true;
fred[3] = "Wow";

I place the array access operator ([]) next to the name of the pertinent array (fred), and put the number of the array position that I want between the square-braces of the operator. I use the "gets" or "assignment" operator to put information into each of the array positions. Again, any type of data may be placed into an array position, including objects or other arrays.

I could then PULL or EXTRACT information from a position in the array using the same array access operator ([]).

Example (abbreviated)

var myData = fred[0];

In the above example, I have pulled information from the array fred at its 0 position, and placed that data into the variable, myData. If this array were the same as the one in the previous example, myData would now contain the string, "Hi".

Note on pronunciation: fred[0] would be referred to as "fred sub zero", fred[1] would be referred to as "fred sub one", etc.

There is a second way to initialize arrays which involves passing arguments to the Array() constructor during the declaration of the array.

Example:

var fred = new Array("Hi", 127, true, "Wow");

As you can see in the above example, I have passed all of my initial values for the array as arguments of the Array constructor; this is a terrific shorthand for initializing arrays quickly and easily.

Arrays are a very powerful data storage mechanism which, like loops, are a whole world unto themselves. A JavaScript programmer will be called upon to create arrays in profusion to store every kind of data imaginable. In fact, virtually every element on an HTML page is stored in some sort of an array, which you may then access via JavaScript.

Main Menu