Array in JavaScript

In this tutorial, we will learn about Array in JavaScript. If you ever learn any other programming language then you would have a clear idea about Array. For those who are listening to this word for the very first time. The array is a collection of similar type of data elements. We use a single literal to fetch or add data in Array. There are three ways to define an array in JavaScript.

  • Using Array literal
  • Using a new keyword
  • Using Array constructor

We will understand each method to create Array with help of example.

Using Array literal:

In this method we directly define literal we define all elements of an array in square brackets. Mean we define and initialize the array together. As shown in Example.

<script>  
var students=["Raj","Sanjeev","Kishore"];  
for (num=0;num<students.length;num++){  
document.write(students[num] +  " ");  
}  
</script>

Using new keyword:

In this method we directly define literal we define all elements of an array in square brackets. Mean we define and initialize the array together. As shown in Example.

<script>  
var students=["Raj","Sanjeev","Kishore"];  
for (num=0;num<students.length;num++){  
document.write(students[num] +  " ");  
}  
</script>

Using new keyword:

in this method, we create array using the new keyword. Then we assign a value on different indexes of array. Following example will help you to understand it clearly.

<script>  
var num;  
var students = new Array();  
students[0] = "Raj";  
students[1] = "Sanjeev";  
students[2] = "Kishore";  
for (num=0;num<students.length;num++){  
document.write(students[num] + " ");  
}  
</script>

Using Array constructor:

In this method, we pass values in Array Constructor while instantiating Array. Check the following example.

<script>  
var students=new Array("Raj","Sanjeev","Kishore");  
for (num=0;num<students.length;num++){  
document.write(students[num] + " ");  
}  
</script>
Spread the love