Arrays

Arrays are simply lists of values. If you like, a an array is a variable which can hold more than one element of data and keep them seperate from each other. Arrays are particularly useful when used in combination with loops and descisions.

Whereas variables allow access to the data they contain by name, an array uses a combination of the name of the array and the position in the list the data occupies.

The position of any given chunk of data in an array is known as its index. Indexes begin at 0 for the first item of data in an array and then proceed to 1, 2, 3 and so on as you might expect.

Here is an example:

<script language="javascript" type="text/javascript">

// Define the array
var weekDays = new Array("Sunday","Monday","Tuesday","Wednesday",
                         "Thursday","Friday","Saturday");
                         
// Print the third entry into the page
// The 3rd item in the list has an index of 2
document.write("The third day of the week is <b>" + weekDays[2] + "</b>");

</script>

Live example

Creating arrays

Two methods can be used to create arrays. Firstly, an empty array can be created and then data can be assigned directly to specific indexes. Here is an example:

var myCDCollection = new Array();
myCDCollection[0] = "Nevermind";
myCDCollection[1] = "Appetite for Destruction";
myCDCollection[2] = "Licence to Ill";
myCDCollection[3] = "Hairway to Steven";

Secondly, the array can be created with data passed to the constructor. Here is an example which creates the same array as above using this method:

var myCDCollection = new Array("Nevermind","Appetite for Destruction",
                               "Licence to Ill","Hairway to Steven");

If an array is created using this second method data can still be added or changed using the indcies as with the first method, for example:

// Create the array with 4 items of data
var myCDCollection = new Array("Nevermind","Appetite for Destruction",
                               "Licence to Ill","Hairway to Steven");
                               
// Add 2 new items to the list
myCDCollection[4] = "Live at Budokan";
myCDCollection[5] = "Dummy";

// Change item 2 (index 1)
myCDCollection[1] = "Use Your Illusion 1";

// Array now contains:
//
// 1:  "Nevermind"
// 2:  "Use Your Illusion 1"
// 3:  "Licence to Ill"
// 4:  "Hairway to Steven"
// 5:  "Live at Budokan"
// 6:  "Dummy"

array.length

This helpful method returns the number of data elements in the array. This is very useful when writing loops which need to include all elements of a given array.

var numberOfElements = myArray.length;

What next?

This page is intended to offer a swift overview of arrays. The W3Schools Arrays page covers arrays and their usage in much more detail.

There are no exercises here to help you learn arrays. To see how arrays can be used, move on to loops and descisions section which will use arrays in numerous examples and in some exercises as well.