Define Array in JavaScript

Introduction

 
In this article, we will learn about various ways to define arrays in JavaScript. JavaScript arrays are used to store multiple values in a single variable. 
 
Let's look at the following snippets.
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head runat="server">  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.     <script>    
  8.                     var arr = ['x''y''z']; 1  
  9.         alert(arr[0]);    
  10.     </script>  
  11.     </form>  
  12. </body>  
  13. </html>  
Here we have defined an array using the “var” keyword. Then we are accessing the element of the array at index 0.
 
var keyword
Now we will use an Array() function to create an array.
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head runat="server">  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.     <script>    
  8.         var arr = new Array("Ramesh""Suresh""Hareesh");  
  9.         alert(arr[0]);    
  10.     </script>  
  11.     </form>  
  12. </body>  
  13. </html>  
 
Array function
 
In the following snippet, we are not creating an element at the time of Array () creation.
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head runat="server">  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.     <script>    
  8.                     var arr = new Array();  
  9.         arr[0] = 100;  
  10.         arr[1] = "Rama";  
  11.         arr[2] = "sagar";  
  12.         alert(arr[1] + arr[2]);    
  13.     </script>  
  14.     </form>  
  15. </body>  
  16. </html>  
 
creating element in time of Array creation
 

Summary

 
In this article, we learned various ways to define arrays in JavaScript. In future articles, we will learn some more basic concepts of JavaScript.