JavaScript Multidimensional Arrays Multi-dimensional JavaScript Arrays

We learned how to declare arrays in JavaScript: we saw arrays containing a series elements, none of which was an array. But JavaScript also supports multidimensional arrays: arrays whose elements are arrays.

Tables are good metaphors for multidimensional arrays: rows contain multiple cells; while independent, each cell belongs to the same row. The table is the multidimensional array, and rows, its elements.

Declaring a Multidimensional Array in JavaScript

When we showed you how to declare one-dimensional arrays, we covered three declaration methods. All three can be used with multidimensional arrays; this tutorial only mentions the literal notation and array constructor.

Using the Literal Notation

The same syntax is used to declare multidimensional arrays: we simply "nest" the declaration, as shown below.

// Declare a multidimensional array (literal notation)
var arlene = [ ["A1","A2"], ["B1","B2"], ["C1","C2"] ];

In the JavaScript code above, we created a 3x2 multidimensional array; if it were represented as a table, the array would look like this:


Using the Array Constructor

There is another, more explicit way to declare multidimensional arrays in JavaScript, by creating arrays inside arrays:

// Declare a standard, one-dimensional array
var arlene = new Array();
// Declare arlene's first and second element as arrays
arlene[0] = new Array();
arlene[1] = new Array("I", "learn", "JavaScript");

We first created a standard array, then made it multidimensional by declaring its elements as arrays themselves. We will now show you how to reference array elements in JavaScript, for both one- and multidimensional arrays.

Browser support for JavaScript multidimensional arrays
Internet Explorer supports JavaScript multidimensional arraysFirefox supports JavaScript multidimensional arraysSafari supports JavaScript multidimensional arraysOpera supports JavaScript multidimensional arrays