Next page | Contents page |


Arrays are collections of data items again, but ordered and indexed by a value rather than each having a name. The indexing value is put in square brackets, []. Eg,

  var a = new Array (); // Must first construct Array object
  a [0] = 1.5;
  a [1] = 2.3;
  a [5] = -1;
  a [15] = true;
  a [42] = "Yes";	
  a [52] = { width:100, height:200 };  // What????

Yes, any data type can go in each element, just as any data type can go in each property of an object.

Unlike many languages you do not have to know beforehand how many elements you will need in the array (but if you do you can preallocate by writing var a = new Array (6); or whatever).

The length of an array is a numeric property, a.length, the value of which is one greater than the highest index used so far (because arrays are assumed to start with index 0, not 1).

Notice that the array we defined in the example is sparse. We have only assigned to 6 elements. And so only 6 memory locations are allocated, not 53 as would be the case in many other languages.

Array initialisers

Another way to create an array is with an array initialiser (or array literal). This is very similar to the object literal but using square brackets. Eg,

var cities = ["London", "Belfast", "Cardiff", "Edinburgh"];

(Java programmers will find this confusing because they are used to curly braces for array initialisers. In JavaScript those are used for object initialisers.)

Next page | Contents page |