Arrays

Arrays are an ordered collection of data. Every piece of data contained in an array is identified by a number, called index. The first item is index 0, the second 1, etc. In JavaScript, as in most scripting languages, arrays can hold any kind of data even within the same array: strings, numbers, objects, etc.

In JavaScript, arrays are implemented as objects. They have to be instantiated like objects and also have methods to process the data structure. Arrays are created as follows:

var myArray = new Array(1, "this is a string", myVar);

The keyword var is the constructor of a the new variable myArray, which will be a variable of type Array. The keyword new is the constructor of the data type "Array". The items in parentheses are the data that the array will hold, in this case, a number, a string, and a variable. The number, 1, will be index 0, the string, "this is a string", will be index 1, and the variable, myVar, will be index 2.

Alternatively, the array could be created as follows:

var myArray = new Array(3); // creates the array with space for three items
myArray[0] = 1;
myArray[1] = "this is a string";
myArray[2] = myVar;

Arrays are regular variables and can be changed any time. Provided that an array element at index n exists, the assignment of values is just as in the preceding example.

myArray[n] = [value];

There are also a number of built-in methods to dynamically change, extend, or shorten arrays. See the array methods examples for a demonstration of some.

You should be familiar with the following methods to process array data:

myArray.length
length return the number of elements in the array (which is always one more than the last index).
myArray.sort( )
sort( ) sorts an array in alphabetical order.
myArray.push([value])
push([value]) appends value to the end of the array.
myArray.pop( )
pop() extracts and returns the last item of the array.
myArray.unshift([value]
unshift([value]) inserts value at the from of the array.
myArray.shift( )
shift( ) extracts and returns the first item of the array.