News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

JavaScript Tutorial – 05 – Arrays

JavaScript tutorials

An array is a data structure used for storing a collection of values. In JavaScript, there are three kinds of arrays: numeric, associative, and multidimensional.

Numeric arrays

Numeric or indexed arrays are the most common type and use an index to refer to each of its elements. They can be created in four different ways. First, the array constructor can be used with the array elements specified as the parameters.

var a = new Array(0,1,2);

Second, the elements can be filled in using the array square brackets.

var b = [0,1,2];

The third way is to create an empty array and then use the square brackets to fill it one element at a time. Note that the array index starts with zero and that the capacity of the array is adjusted automatically as more elements are added.

var c = new Array();
c[0] = 0;   
c[1] = 1;   
c[2] = 2;

The fourth and last way of creating an array is by using the array constructor with a single parameter, which will be the initial size of the array. If the maximum number of values that the array needs to hold is known beforehand then this method can be used to slightly improve the performance.

var d = new Array(3);

When reading elements from an array the same square bracket notation is used as when writing to them.

document.write(a[0]);

Note that the elements inside of the array can store any data type, just as regular variables can.

var e = [0, 3.14, "string", true];

Associative arrays

The second kind of array is the associative array, which uses a key string instead of a numerical index. To create one, first declare an empty array and then assign values to the desired keys.

a = new Array();
a["name"] = "Peter";   
a["age"]  = 25;

When reading these elements it’s important to remember the key names, since these arrays cannot be accessed with an index.

document.write(a["name"] + " is " + a["age"]);

In JavaScript, associative arrays are also objects. Therefore, associative arrays can alternatively be accessed using the dot notation.

a.name = "Peter";
a.age  = 25;
document.write(a.name + " is " + a.age);

Multidimensional arrays

Multidimensional arrays can be created by adding arrays as elements to another array. They can have any number of dimensions and for each new dimension there is another set of square brackets.

a = [[0,1,2], [3,4,5], [6,7,8]]; 
a[0][2] = "two";
document.write(a[2][2]); // 8
Recommended additional reading:
Sams - Teach Yourself JavaScript in 24 Hours