An array is a composite data type composed of an ordered set of variables where each variable is known as an element.
Arrays in JavaScript can hold integers, floating-point numbers, Booleans, strings, other arrays as well as values of mixed type.
Creating an Array
The Array() constructor is used to create an array and it can be done in three different ways.
var names = new Array();
This creates a new empty array.
var names = new Array("Dave","John","Fred");
This creates a new array with the supplied values assigned to each element in the array starting from element 0 and array length set to the number of values passed.
var names = new Array(3);
This creates a new empty array with length set to the length passed.
Array Numbering
The index for the first element in an array is 0 by default but it can start at any numeric value you choose.
Accessing Elements in an Array
<script language="javascript" type="text/javascript">
var names = new Array ("Tom", "Dick", "Harry");
// This prints out the second element in the array - Dick
document.write (names[1]);
</script>
Updating Elements in an Array
<script language="javascript" type="text/javascript">
var names = new Array ("Tom", "Dick", "Harry");
// This changes Harry to Dave
names[2] = "Dave";
</script>
Adding Elements to an Array
Although a length may be set when creating an array, this can be changed later by adding additional elements.
Example of Adding Elements to an Array
<script language="javascript" type="text/javascript">
var names = new Array ("Tom", "Dick", "Harry");
names[3] = "Mary";
names[4] = "June";
</script>
To start the array index at a numeric value other than the default 0 or if you wish to leave gaps in the array it can be done as below.
Example of an Array with Gaps
<script language="javascript" type="text/javascript">
var names = new Array ();
Since an array can hold various data types, including other arrays, this allows you to create what are effectively multidimensional arrays.
Example of a Two Dimensional array
<script language="javascript" type="text/javascript">
var names = new Array ();
var addresses = new Array ();
var details = new Array (names, addresses);