Javascript TUTORIAL for beginners

We will extend the concept of array to a a two dimensional array. Since it is a mathematical topic, let us begin with the example that prints a one dimensional array. All elements of the array has 0 at its value.

 ``` ```

You may like to try this example here .

Notice that we have used writeln in place of write in this example. In theory, it adds a newline \n at the end of output. In practice it does not make a difference, since HTML ignores the newline anyway.

There is nothing special here. With the statement

var x = [];

we declare that x is an array. we do not need to specify the size. In the first for loop we have defined all four elements of the array as having value 0. In the next for loop we print the 4 values which look as

0 0 0 0

What if we wish to extent x to contain 3 rows in place of just one ? We need  a two dimensional array. Closely look at the following example

 ``` ```

You may like to try this example here .

It will give the following output

0 0 0 0
0 0 0 0
0 0 0 0

Well there is nothing fancy in the program, but you need to pay attention to how a 2D array is declared. Look at the code

for ( j=0; j<=2 ;j++)
{
x[j] = [];
}

The statement tell us that x[0] is an array, x[1] is and array and x[2] is an array. If x[0] is an array, then its elements are to be accessed as x[0][0],x[0][1], x[0][2] etc...

And therefore, we initialize the values of the elements of the 2D array as

for ( j=0; j<=2 ; j++)
{
for ( i=0; i<=3 ; i++)
x[j][i] = 0;
}

The code

for ( j=0; j<=2 ; j++)
{
for ( i=0; i<=3 ; i++)
document.writeln(x[j][i]);

document.writeln("<br />");

}

just prints the 2D Array values.

The program does not do anything much valuable. But it will help understand you initial part of 2D array. Let us now write a more meaningful program that will print multiplication table.

The following program prints out the multiplication tables of 7, 8, 9 and 10.

 ``` ```

You may like to try this example here .
Here is how it gives output

7 8 9 10
14 16 18 20
21 24 27 30
28 32 36 40
35 40 45 50
42 48 54 60
49 56 63 70
56 64 72 80
63 72 81 90
70 80 90 100