Creating Arrary in JavaScript

Create an Array

An array can be defined in three ways.

The following code creates an Array object called myCars:

Listing 1:

1
2
3
4
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab";       // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";

Listing 2:

1
var myCars=new Array("Saab","Volvo","BMW"); // condensed array

Listing 3:

1
var myCars=["Saab","Volvo","BMW"]; // literal array

Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.


Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.

The following code line:

1
document.write(myCars[0]);

will result in the following output:

1
Saab

Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:

1
myCars[0]="Opel";

Now, the following code line:

1
document.write(myCars[0]);

will result in the following output:

1
Opel