Google News
logo
JavaScript Arrays
An array is a special type of variable, which can store multiple values using special syntax. Every value is associated with numeric index starting with 0. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
var <array-name> = [element0, element1, element2,... elementN];
Javascript Array literal :
<html>
<head>
<title>Javascript Array literal</title>
</head>
<body>
 
<script type="text/javascript">
var emp_names=["V V R Reddy","V V Ramana Reddy","V Venkataramana Reddy"];  
for (i=0;i<emp_names.length;i++){  
document.write(emp_names[i] + "<br/>");  
}  
</script> 
 
</body>
</html>
Output :

V V R Reddy

V V Ramana Reddy

V Venkataramana Reddy

Javascript Array Constructor :
You can initialize an array with Array constructor syntax using new keyword
var arrayName = new Array();
 
var arrayName = new Array(Number length);
 
var arrayName = new Array(element1, element2, element3,... elementN);
Example :
<html>
<head>
<title>Javascript Array Constructor</title>
</head>
<body>
 
<script type="text/javascript">
 
var web=new Array("http://freetimelearn.com", "http://freetimelearning.com", "http://www.freetimelearning.com");  
for (i=0;i<web.length;i++){  
document.write(web[i] + "<br>");  
}  
 
</script>  
</body>
</html>
Output :

http://freetimelearn.com

http://freetimelearning.com

https://www.freetimelearning.com

Javascript Accessing Array Elements  :
JavaScript arrays are a special type of object. To access an array item, the [] operator is used, for example colors[2]. The [] operator converts the expression inside the square brackets to a string.
Example :
<html>
<head>
<title>Javascript Accessing Array Elements</title>
</head>
<body>
 
<p id="str_1"></p>
<p id="str_2"></p>
<p id="str_3"></p>
<p id="str_4"></p>
<p id="int_1"></p>
<p id="int_2"></p>
<p id="int_3"></p>
<p id="int_4"></p>
 
 
<script type="text/javascript">
 
var stringArray = new Array("one", "two", "three", "four");
 
document.getElementById("str_1").innerHTML = stringArray[0]; 
document.getElementById("str_2").innerHTML = stringArray[1]; 
document.getElementById("str_3").innerHTML = stringArray[2]; 
document.getElementById("str_4").innerHTML = stringArray[3]; 
 
var integerArray = [1, 2, 3, 4];
 
document.getElementById("int_1").innerHTML = integerArray[0]; 
document.getElementById("int_2").innerHTML = integerArray[1]; 
document.getElementById("int_3").innerHTML = integerArray[2]; 
document.getElementById("int_4").innerHTML = integerArray[3]; 
 
</script>
 
</body>
</html>
Output :

one

two

three

four

1

2

3

4