Skip navigation.
Home

Defining an array in JavaScript

There are 3 ways of defining an array in JavaScript, each with its own charm.

1) Conventional array

The classic conventional array looks like the following:

var mystudents=new Array()
mystudents[0]="Bob"
mystudents[1]="Jane"
mystudents[2]="Peter"

You can expand and contract the array as desired, by adding new array
elements. Note that like in most other programming languages, the first array
element should have an index number of 0.

With a conventional array, you have the option of presetting the array's
length when defining it, by passing in a numeric integer into the Array()
constructor:

var mystudents=new Array(3)

In this case 3 array elements will automatically be created, each with a
value of "undefined." It also means probing the property
mystudents.length will return 3.

2) Condensed array

The second way of defining an array is called a condensed array, and
differs from the above simply in that it allows you to combine the array and
array elements definitions into one step:

var mystudents=new Array("Bob", "Jane", "Peter", 14, 54)

This is convinient if you know all the array element values in advance.

3) Literal arrays

Finally, we arrive at literal arrays. Introduced in JavaScript1.2
and support by all modern browsers (IE/NS4+), literal arrays sacrafice
intuitiveness somewhat in exchange for tremendous robustness. The syntax looks
like:

//literal array with 3 elements
var mystudents=["Bob", "Jane", "Peter"]

//literal array with 5 elements (middle 3 with undefined values).
var mystudents=["John", , , "Chris"] 

As you can see, enclose all the array elements within an outter square
bracket ([ ]), each seperated by a comma (,). To create array elements with an initial undefined value,
just enter a
comma (,), as shown in the second example above.

Literal arrays really shine when it comes to defining multi-dimensional
arrays. It is as easy as adding containing brackets ([]) within the outermost
bracket. For example:

var myarray=[["New York", "LA", "Seattle"], China, Japan]

Here the first array element is actually a two dimensional array in itself
containing various cities names. To access LA, then, you'd use the syntax:

myarray[0][1] //returns "LA"

Here's an array with its 1st element in turn being a 3 dimensional array:

var myarray=[[[2,4,6]], China, Japan]

Just remember, the more brackets you use, the deeper the hole you dig!