Accessing a dimensional array in JavaScript

Let’s declare a two dimensional array and try to access the element. Here is the first example:

var array = [[1, 2, 3],[4, 5, 6]];
alert(array[1][1]);
// Output: 5

Here is the same sample but with another sytnax:

var array = new Array(2);
array[0] = new Array(3);
array[0][0] = 1;
array[0][1] = 2;
array[0][2] = 3;
array[1] = new Array(3);
array[1][0] = 4;
array[1][1] = 5;
array[1][2] = 6;
alert(array[1][1]);
// Output: 5

Again, another syntax of this example to access a javascript array:

var array = new Array(new Array(1, 2, 3), new Array(4, 5, 6));
alert(array[1][1]);
// Output: 5

Some developers make the following error when accessing a JavaScript array and wait that the 5 will be returned:

var array = [[1, 2, 3],[4, 5, 6]];
alert(array[1,1]);
// Output: [4, 5, 6]

JavaScript interpretes 1,1 as a comma separated expression and this expression returnes 1. Each part of the comma separated expression is executed left to right. The final value of the comma separated expression is the value of the last comma part. So, when you try to evaluate the following script in the sample below you will get the last array item because the value of the comma separated expression 0,1,2 will be 2:

var array = [1, 2, 3];
alert(array[0,1,2]);
// Output: 3