JavaScript Arrays

In JavaScript, an array is a special type of variable that can contain multiple values. The following variable, 'fname', has been defined and initialised with the name 'Bob'.

var fname = "Bob";

If multiple names needed to be stored, instead of having a different variable for each, an array could be used. Here, three names are added to the array 'fname' when it is defined.

var fname = ["Bob", "Fred", "George"];

As well as being able to add the elements to an array when it is defined, it is also possible to add them using the 'push' method at a later point in time.

var fname = [];


The elements in an array can be accessed using their corresponding index number, with the first element in an array having an index number of zero, so, for example, 'George' has an index number of two and can be output to the screen as follows.


In order to display all of the elements in an array a 'for' loop can be used.

for (i = 0; i < fname.length; i=i+1)
   document.write(fname[i] + "<br>");

The above example uses the 'length' property of an array to determine the number of elements within it and therefore the number of times to go through the loop. The resulting output will list all the elements of the array on a separate line.


If is necessary to display all the values in an array together, on the same line, then the methods 'toString' and 'join' can be used, both of which produce slightly different results. The 'toString' method displays the array elements on one line, separated with commas and no spaces. There is no way to specify the separator between the elements.



The 'join' method provides much greater flexibility, allowing for the separator to be specified. Here, a comma and space are used to separate items.

document.write(fname.join(", "));

Bob, Fred, George

As with any variable, an element in an array can be updated. The following example updates the name 'Fred' in element one of the array to 'Freida' and then displays it.

fname[1] = "Freida";

In order to remove a value from an array, there are a number of different options available, depending on which value needs to be removed. The 'pop' method can be used to remove the last item in the array.


If it is necessary to remove the first item instead of the last, the 'shift' method can be used to achieve this.


It is also possible to remove a value from an array using 'delete', although this does leave a blank element rather than completely removing it. Here the element with an index value of one is left blank.

delete fname[1];

As mentioned previously, the 'pop' method can be used to add new elements to the end of an array. If it is desired to add them at the start instead, then the 'unshift' method can be used.