JavaScript Array

An Array is a collection of values stored in adjacent memory locations.
JavaScript array is an object that represents a collection of similar type of elements.

Java script support two type of array
1) Single dimension array
2) Multi-dimension array
There are 3 ways to construct array in JavaScript
1) By array literal
2) By creating instance of Array directly (using new keyword)
3) By using an Array constructor (using new keyword)


JavaScript array literal

Syntax of creating array using array literal

var arrayname=[value1,value2.....valueN];


Example-

<html>
<body>
<script>
var emp=["Gaurav","Ankita","Kanchan"];
for (i=0;i< emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>

Output


JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

var arrayname=new Array();

Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.

<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i< emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>

OUTPUT


Example-2

<html>
<body>
<script>
var marks=new Array(5);
var sum=0;
for(i=0;i< marks.length;i++)
{
marks[i]=parseInt(prompt("Enter Marks:"));
sum=sum+marks[i];
}
alert("sum="+sum);
alert("Averge of marks="+(sum/marks.length));
</script>
</body>
</html>

JavaScript array constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide value explicitly.
The example of creating object by array constructor is given below.

<html>
<body>
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i< emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>

OUTPUT


Multi- Dimensional Array

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns.


Syntax

var variable_name=new Array(size);//declaration
variable_name[index]=new Array(value1,value2,....)//initialization


Example

<html>
<body>
<script>
var i,j;
var arr=new Array(2);
arr[0]=new Array(1,23);
arr[1]=new Array(2,23);
for(i=0;i< arr.length;i++)
{
for(j=0;j< arr.length;j++)
{
alert(arr[i][j]);
}
}
</script>
</body>
</html>