Javascript TUTORIAL


Javascript Array


Let assume that we have to calculate the area of 5 rectangles. We can declare 5 variables each for length and width and then another 5 variables for the area as follows.

Let us take a look at the following code.



var length1,length2,length3,length4,length5;
var breadth1,breadth2, breadth3,breadth4, breadth5;
var area1,area2, area3, area4,area5 ;


While this is pefectly correct to define the variables in this way, javascript provides the concept of array.Here is how you do the same thing using arrays.

<html>
<body>
<script type="text/javascript">

/*
************************************************************
Example - Javascript Array Object
************************************************************
*/

var length = new Array(5);
var breadth = new Array(5);
var area = new Array(5);

</script>
</body>
</html>



The statement var length = new Array(5) says that length is an array of 5 elements. The first element is accessed usng length[0].

Let us now go ahead an write a program that will print the areas of 5 rectangles.



<html>
<body>
<script type="text/javascript">
<!--
var length = new Array(5);
var breadth = new Array(5);
var area = new Array(5);
var i;

length[0] = 10;
length[1] = 20;
length[2] = 30;
length[3] = 40;
length[4] = 50;

breadth[0] = 5;
breadth[1] = 15;
breadth[2] = 25;
breadth[3] = 35;
breadth[4] = 45;

for (i = 0; i <= 4; i++)
{
area[i] = length[i] * breadth[i];
document.write("Area [",i,"] = ");
document.write(area[i]);
document.write("<br/>");
}
//-->
</script>
</body>
</html>
If we execute the code we get the following output

Area [0] = 50
Area [1] = 300
Area [2] = 750
Area [3] = 1400
Area [4] = 2250


Arrays help organize the codes.Note that the array index starts from 0 and not 1. You can try the example online at Example - Javascript Array

We have touched only a very small area of array. Array is a vast tppic, and we have covered lot more material that you can access by choosing one of the topics on the right.
More Array Topics
Creating New Array
Array Initialization
2 Dimensional Array
Array Length
Adding elements in Array
Array push method
And more ....