3.1 Creating a Simple Array

NN 3, IE 4

3.1.1 Problem

You want to create a simple array of data.

3.1.2 Solution

JavaScript provides both a long way and a shortcut to generate and populate an array. The long way is to use the Array object constructor. If you specify no parameters for the constructor, you create an empty array, which you may then populate with data entry by entry:

var myArray = new Array( );
myArray[0] = "Alice";
myArray[1] = "Fred";

You do not have to declare a fixed size for an array when you create it, but you may do so if you wish, by passing a single integer value as a parameter to the constructor method:

var myArray = new Array(12);

This creates an array of 12 entries whose values are null.

If you supply more than one comma-delimited parameter to the constructor method, the arguments are treated as data for the array entries. Thus, the following statement:

var myArray = new Array("Alice", "Fred", "Jean");

creates a three-item array, each item containing a string value.

A shortcut approach to the same action lets you use square brackets to symbolize the array constructor:

var myArray = ["Alice", "Fred", "Jean"];

You can use the shortcut syntax in IE 4 or later and NN 4 or later.

3.1.3 Discussion

After you create an array (through any of the syntaxes just shown), you can add to it by assigning a value to the array with the next numeric index in sequence. If your script doesn't know how large an array is when it needs to add to it, you can use the length property of the array to help out. Because the length integer is always one larger than the highest zero-based index value of the array, the length value can act as the index for the next item:

myArray[myArray.length] = "Steve";

In fact, you can use this construction to populate any existing array object, including an empty one. This is particularly helpful if you are populating a large array and need to change values in the source code from time to time. Rather than trying to juggle fixed index numbers in a long series of assignment statements, use the length property, and order the assignment statements so that all items are in the desired array order. The indexes will take care of themselves when the statements run, even if you change the order in the source code tomorrow.

3.1.4 See Also

Recipe 3.2 for creating a more complex array; Recipe 3.8 for a discussion about creating an array of objects; Recipe 3.3 for converting an array's entries to a string value.