An array is a set of variables (e.g., strings or numbers) that are grouped together and given a single name.
For example, an array could be used to hold a set of strings representing the names of a group of people. It might be called people and hold (say) four different strings, each representing the name of a person:
Items are held in an array in a particular order, usually the order in which they were added to the array. However, one of the great advantages of arrays is that the ordering can be changed in various ways. For example, the array above could easily be sorted so that the names are arranged in alphabetical order.
To create an array, a new Array object must be declared. This can be done in two ways:
In the first example, the new
Array object is declared explicitly.
In the second example, the array is declared in much the same way a string might be declared, except that square brackets (
Arrays are often used to hold data typed-in or otherwise collected from a user. Therefore, it may be necessary to create the array first and add data to it later. An empty array may be created in the following way:
The array thus created has no elements at all, but elements can be added as necessary later.
If it is not known exactly what data will be stored in the array, but the number of items is known, it may be appropriate to create an array of a specific size. This may be done in the following way:
The array thus created has four elements, all of which are empty. These empty elements can be filled with data later on.
Suppose an array has been created using the following code:
var demoArray = new Array("Sarah","Patrick","Jane","Tim");
The number of elements in the array can be determined using the
length property. For example: