Arrays in JavaScript are extremely useful for storing and manipulating information you have coded directly into the script, or information collected from the browser. In this article, Dan Wellman details how to use and manipulate them.
The array is one of a number of objects built directly into JavaScript. Think of them simply as variables containing multiple values. They can hold string or numerical values, have no maximum boundaries (although the speed at which your scripts are interpreted will decrease as the amount of data increases) and are comma delimited. They have no persistence, meaning that their values are not held once the page containing the script has closed or reloaded.

The aim of this article is to show you how information can be hard-coded into your scripts and how that information can be addressed and used to enhance your Web pages. The example script will focus just on one dimensional arrays.

Single Dimensioned Arrays

A simple example of a single-dimensioned array is:

myArray = new Array(15,89,4,61,5)

Which simply says create an array called myArray with five values, the values are integers and equal 15, 89, 4, 61 and 5. This information, were it to mean anything, could then be manipulated in all kinds of ways; you could print the results on the page using the simple command:


That would display 15 on the page. You could also perform simple math, were the need to arise:

var mySum = myArray[1] * myArray[2]

which displays the number 356.

An important property of the array object is the length property; the extremely basic numerical array above has a length of five. Each of the values in the array can be accessed using their index within square brackets following the array name, for example:


It’s important to remember that the indices of any array always begin with 0 representing the first item in the array; therefore, while the length property of this very simple array is five, the highest index is four.