# Multi-dimensional arrays in Javascript

Multi-dimensional arrays in Javascript
0

#1

Why does it equal both the numbers inside and outside of the brackets? I understand that [3] is [[10, 11, 12]…], but that not why that includes […13, 14].

var arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]

#2

Arrays work like that.
arr[0] is [1,2,3]
arr[1] is [4,5,6]
arr[2] is [7,8,9]
arr[3] is [[10,11,12],13,14]
arr[3][0] is [10,11,12]
arr[3][1] is 13
arr[3][2] is 14
That’s pretty consistent.
If arr[3] wasn’t [[10,11,12], 13, 14] that would be inconsistent, since [10,11,12] is nested inside index 3 of arr.

#3

Everything before each comma (and after the last comma) is considered a single element in the array, no matter what it is—and even if it’s another array, as in that example. Going by the principle that the array elements can be anything, they can even be another multi-dimensional array, which is why arr[3] is is the full [[10,11,12], 13, 14], since it comes after the last comma. The brackets really have nothing to do with what’s considered an array element, it’s entirely about the full element after that last comma. Could be a string, an object, whatever.

#4

I agree with astv99 in his analysis, but just to make a point that might clear up some confusion on the part of the OP, in JS there are no true multidimential arrays, like there are in other languages. In C, you might have arr[i, j], but in JS, it’s arr[i][j].

It’s a subtle difference, but in JS you only have one dimensional arrays. To get the functionality of a 2d array, you make a one-dimensional array of one-dimensional arrays. So, whereas in C, you can have a 3X4 array of values, in JS, you have an array of 3 elements and each of those elements is itself an array of 4 elements. It can work basically the same as 3X4 two dimensional array, but as astv99 points out, JS doesn’t limit what you put in there. It’s up to the programmer to control what goes into that array or subarray and how it’s used.