Creating arrays in JavaScript

In addition to simple data types, JavaScript supports a more complicated data type knows as an array. An array is an ordered collection of values that is grouped together by a single variable name. The syntax for creating an array is:

var arrayName = new Array (size);

The arrayName is the name of the array variable and the size is the number of elements or distinct values in the array. Note specifying size is optional when creating the array. If you don't specify a size, JavaScript will automatically increase the size of an array as you add more elements to the array.

If you have not worked with arrays in any programming language before, the following display may help you to understand the concept of array:

index 0 1 2 3
value JavaScript HTML ASP Scripting tools

The above visualization shows an array of size 4. Note the array index starts at 0 so the first element of an array is stored at index 0, the second is stored at index 1, etc. An index refers to an integer that identifies the location of an element. For instance, the index value is 4 for the element "Scripting tools."

So you might be thinking when should I use an array or a variable? With a variable, you can store only one value at a time. If you had to store, let's say, 40 different values to a related item, you could declare 40 variables. But managing that many variables would be insufficient. So use an array instead of size 40. As a concrete example, assume you wanted to store in your JavaScript code the names of the months in a year. To do this you could declare an array of size 12 as:

var monthArr = new Array (12);

instead of declaring 12 different variables for the names of each month as:

var jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec;

In some problems, it becomes obvious to use an array instead of a variable. For instance, assume you have 40 students in your class and you want to compute the average grade on the mid-term for these students. To do that, you do not want to create 40 variables, like var st1MidTermScore, st2MidTermScore, etc... Instead, you should create an array like:

var stMidTermScoreArr = new Array (40);

Next, read about: