Javascript Arrays

In JavaScript, an array is an object that represents a collection of similar type of elements.

Each value is called an element specified by an index. It has the following characteristics:-

  • An array can hold values of different types. For example, we can have an array that stores the number and string, and boolean values.
  • The length of an array is dynamically sized and auto-growing. In other words, we don’t need to specify the array size upfront.

We can construct an array in the following ways:-


JavaScript array literal

The syntax of creating array using array literal is given below:

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

As we can see, values are contained inside [ ] and separated by , (comma). Let’s understand it by creating and using array in the following example.

Input:-
<script>  
   var emp=["Matt", "Jenny", "Mike"];  
   for (i=0;i<emp.length;i++){  
   document.write(emp[i] + "<br/>");  
   }  
</script> 

Output:-


JavaScript Array directly (new keyword)

The syntax of creating array directly using new keyword is given below:

var arrayname=new Array();  

Here, new keyword is used to create instance of array.Let’s understand it by creating and using array in the following example

Input:-
<script>  
   var i;  
   var emp = new Array();  
   emp[0] = "Matt";  
   emp[1] = "Jenny";  
   emp[2] = "Mike";  
   
   for (i=0;i<emp.length;i++){  
   document.write(emp[i] + "<br>");  
   }  
</script>

Output:-


JavaScript Array constructor (new keyword)

We need to create instance of array by passing arguments in constructor so that we don’t have to provide value explicitly.

Let’s understand it by creating and using array in the following example.

Input:-
<script>  
   var emp=new Array("Matt","Jenny","Mike");  
   for (i=0;i<emp.length;i++){  
   	document.write(emp[i] + "<br>");  
   }           
</script>

Output:-


Changing an Array Element

This helps in changing the value of array element. Following is the example to illustrate it:-

Input:-
<script>  
   var student = ["Matt", "Jenny", "Mike"];
   student[0] = "Sophie";
   document.write(student + "<br>");  
</script>

Output:-


Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns “object” for arrays.

But, JavaScript arrays are best described as arrays.

var person = ["Matt", "Voss", 46]; //Array
var person = {firstName:"Matt", lastName:"Voss", age:46}; //Object