Multidimensional Arrays in Javascript

Defining arrays in Javascript turns out to be a bit tricky. You can’t just predeclare the dimensions, you have to initiate them by defining the actual values for each element, dimension by dimension. For a one-dimensional array with three elements we can do this a couple of different ways.

In both cases the mechanism that defines the actual size of the array is the act of assigning values to the elements. Initialization of two-dimensional arrays works the same way.

This works because all of the elements are initially populated in order. The interpreter continually expands the definition as elements are defined. These methods work for arrays of three or more dimensions as well. That said, declaring and populating arrays of three or more dimensions is best accomplished using the new and loop method. Trying to declare higher-dimensioned arrays directly gets painful rather quickly. This is even true of one- or two-dimensional arrays if one dimension is quite large.

One might be tempted to try the following shortcut on the theory that the interpreter will just have to allocate what it needs, but we find that it doesn’t work.

The process feels a bit cumbersome but it is what it is. Once an array is defined as it needs to be it can used anywhere in a program and can even be passed as a parameter to a function, where statements internal to that function will interpret the array and its dimensioning correctly.

This entry was posted in Software and tagged , , . Bookmark the permalink.

2 Responses to Multidimensional Arrays in Javascript

  1. Link says:

    Javascript does not support two dimensional arrays, instead we store an array inside another array and fetch the data from that array depending on what position of that array you want to access. Remember array numeration starts at ZERO .

  2. Technically correct, yes. There’s no telling exactly *where* the memory for any specific array or sub-array will be placed in memory as the heap manager does its thing. One couldn’t somehow map another object onto the original array (as in a variant record or free union) and expect the elements to be contiguous and in order as you might in a pre-processed language like C, C++, FORTRAN, or Java. From the point of view of the programmer, however, it *looks* like a two-dimensional array, which suits my purposes.

    It is clear that JavaScript arrays are zero-based.

    It could be argued that it’s madness to do calculations beyond a certain complexity in JavaScript, but these exercises have helped me get used to the language in a context I understand.

Leave a Reply

Your email address will not be published. Required fields are marked *